Skip to content

Instantly share code, notes, and snippets.

@ForbesLindesay
Created May 21, 2012 00:07
Show Gist options
  • Save ForbesLindesay/2760000 to your computer and use it in GitHub Desktop.
Save ForbesLindesay/2760000 to your computer and use it in GitHub Desktop.
Every, Some and Reduce
Array.prototype.every = function (fn) {
return this.reduce(function (a, b){ return a && fn(b); }, true);
}
Array.prototype.reduce = function reduce(accumulator, start) {
var curr, i;
if (arguments.length == 1) {
curr = this[0]; // Increase i to start searching the secondly defined element in the array
i = 1; // start accumulating at the second element
}
else {
curr = start;
i = 0;
}
for (i = i || 0 ; i < this.length ; ++i) {
curr = accumulator(curr, this[i]);
}
return curr;
};
Array.prototype.some = function (fn) {
return this.filter(fn).length > 0;
}
Array.prototype.some = function (fn) {
return this.reduce(function (a, b){ return a || fn(b); }, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment