Created
November 9, 2009 13:09
-
-
Save keeto/229931 to your computer and use it in GitHub Desktop.
MooTools implementation for Array.reduce() and Array.reduceRight()
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
/* | |
Script: Array.Reduce.js | |
MooTools implementation for Array.reduce() and Array.reduceRight() | |
Acknowledgement: | |
- Implementation code ported and reworked from Mozilla's Array.reduce() and Array.reduceRight() algorithms. | |
cf: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce, | |
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight | |
*/ | |
Array.implement({ | |
reduce: function(fn, initial, bind){ | |
var len = this.length, i = 0; | |
if (len == 0 && arguments.length == 1) return null; | |
var result = initial || this[i++]; | |
for (; i < len; i++) result = fn.call(bind, result, this[i], i, this); | |
return result; | |
}, | |
reduceRight: function(fn, initial, bind){ | |
var len = this.length, i = len - 1; | |
if (len == 0 && arguments.length == 1) return null; | |
var result = initial || this[i--]; | |
for (; i >= 0; i--) result = fn.call(bind, result, this[i], i, this); | |
return result; | |
} | |
}); | |
Array.alias({reduce: 'foldl', reduceRight: 'foldr'}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment