News for hackers. Stuff that matters.
Re:Array Iteration Interview Problem by AustinYun on Thursday August 02, 2012 @06:20AM (#4328080)
Here's my second Javascript draft. I intend to refactor it tomorrow so that the three if branches are unrolled into their own functions. Especially since some bizarre facet of Javascript's type coercion makes it impossible to do early returns inside the iterator function ([] << 1 somehow comes out as 1, not [1]).

https://github.com/austinyun/challenges/blob/master/array-it...

    function increment_where_pure(array, match, n) {
        var count;
    
        function iterator(f, acc, item) {
            // f is the function used to combine array arguments -- push || unshift
            if (count === 0) {
                f.call(acc, item);
            } else {
                if (item === match) { item += 1; }
                f.call(acc, item);
                count -= 1;
            }
            return acc;
        }
    
        if (n === 0) {
            return _.map(array, function(item) {
                return item === match ? item + 1 : item;
            });
        }
    
        if (n > 0) {
            count = n + 1;
            return _.reduce(array, iterator.bind(null, Array.prototype.push), []);
        }
    
        if (n < 0) {
            count = -n + 1;
            return _.reduceRight(array, iterator.bind(null, Array.prototype.unshift), []);
        }
    }

There are no comments on this comment yet.