add Array.prototype.reduceRight

This commit is contained in:
rolux 2012-05-25 15:16:21 +02:00
parent d8a88c7f47
commit 223323ac82

View file

@ -99,13 +99,13 @@ if (!Array.prototype.map) {
// see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce // see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
if (!Array.prototype.reduce) { if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fn, ret) { Array.prototype.reduce = function(fn, ret) {
if (this === void 0 || this === null || typeof fn !== 'function') { if (this === void 0 || this === null || typeof fn !== 'function') {
throw new TypeError(); throw new TypeError();
} }
var arr = Object(this), var arr = Object(this),
i, i,
len = this.length; len = arr.length;
if (!len && ret === void 0) { if (!len && ret === void 0) {
throw new TypeError(); throw new TypeError();
} }
@ -113,7 +113,32 @@ if (!Array.prototype.reduce) {
ret = arr[0]; ret = arr[0];
i = 1; i = 1;
} }
for (i = i || 0; i < len ; ++i) { for (i = i || 0; i < len; i++) {
if (i in arr) {
ret = fn.call(void 0, ret, arr[i], i, arr);
}
}
return ret;
};
}
// see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function(fn, ret) {
if (this === void 0 || this === null || typeof fn !== 'function') {
throw new TypeError();
}
var arr = Object(this),
i,
len = arr.length;
if (!len && ret === void 0) {
throw new TypeError();
}
if (ret === void 0) {
ret = arr[len - 1];
i = len - 2;
}
for (i = i || len - 1; i >= 0; i--) {
if (i in arr) { if (i in arr) {
ret = fn.call(void 0, ret, arr[i], i, arr); ret = fn.call(void 0, ret, arr[i], i, arr);
} }