Skip to content

Instantly share code, notes, and snippets.

@keeto
Created November 9, 2009 13:09
Show Gist options
  • Save keeto/229931 to your computer and use it in GitHub Desktop.
Save keeto/229931 to your computer and use it in GitHub Desktop.
MooTools implementation for Array.reduce() and Array.reduceRight()
/*
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