Created
May 21, 2012 00:07
-
-
Save ForbesLindesay/2760000 to your computer and use it in GitHub Desktop.
Every, Some and Reduce
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
Array.prototype.every = function (fn) { | |
return this.reduce(function (a, b){ return a && fn(b); }, true); | |
} |
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
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; | |
}; |
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
Array.prototype.some = function (fn) { | |
return this.filter(fn).length > 0; | |
} |
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
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