Created
August 3, 2012 02:05
-
-
Save austinyun/3243470 to your computer and use it in GitHub Desktop.
Array Iteration Interview Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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