Skip to main content
1 of 3

javascript Redis LREM

I implemented a redis-like plugin for basil.js and had some difficulties implementing particularly the LREM method. The complexity was to loop only once (and not the whole array avery time if we have 0 !== count) ascending or descending. My code below works and pass tests, but I were wondering if another smarter implementation (less intermediary vars) was possible. Thanks for your lights:

        lrem: function (key, count, value) {
            if ('undefined' === typeof count || 'undefined' === typeof value)
                throw new Error('ERR wrong number of arguments for \'lrem\' command');

            var list = this.get(key) || [];

            if (0 === list.length)
                return 0;

            // added here for Basil, even if objects are supported
            // we to not support (yet?) object comparison, too heavy
            if ('number' !== typeof value && 'string' !== typeof value)
                throw new Error('ERR syntax error');

            var index = count >= 0 ? 0 : list.length - 1,
                length = list.length,
                iteration = 0,
                removed = 0;

            // iterate on whole list or stop if we found exactly the right count occurences
            while (iteration < length && (0 === count || (0 !== count && removed !== Math.abs(count)))) {

                if (value === list[index]) {
                    list.splice(index, 1);
                    removed++;

                    // we removed an element, we need to decrease index if we are
                    // looping from 0 to length otherwise we'll skip some values..
                    if (count >= 0)
                        index--;
                }

                iteration++;
                count >= 0 ? index++ : index--;
            }

            if (0 === list.length)
                this.remove(key);
            else
                this.set(key, list);

            return removed;
        }

Here is the whole source.