4 ms·
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 b
by AustinYun 14y ago
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-iteration-interview-problem/add1.js 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), []);
}
}