Skip to content

Instantly share code, notes, and snippets.

@austinyun
Created August 3, 2012 02:05
Show Gist options
  • Save austinyun/3243470 to your computer and use it in GitHub Desktop.
Save austinyun/3243470 to your computer and use it in GitHub Desktop.
Array Iteration Interview Problem
var _ = require("underscore")._;
// No mutation version
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), []);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment