Created
January 5, 2009 11:11
-
-
Save os0x/43358 to your computer and use it in GitHub Desktop.
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
if (!Array.prototype.reduce) | |
{ | |
Array.prototype.reduce = function(fun /*, initial*/) | |
{ | |
var len = this.length; | |
if (typeof fun != "function") | |
throw new TypeError(); | |
// no value to return if no initial value and an empty array | |
if (len == 0 && arguments.length == 1) | |
throw new TypeError(); | |
var i = 0; | |
if (arguments.length >= 2) | |
{ | |
var rv = arguments[1]; | |
} | |
else | |
{ | |
do | |
{ | |
if (i in this) | |
{ | |
rv = this[i++]; | |
break; | |
} | |
// if array contains no values, no initial value to return | |
if (++i >= len) | |
throw new TypeError(); | |
} | |
while (true); | |
} | |
for (; i < len; i++) | |
{ | |
if (i in this) | |
rv = fun.call(null, rv, this[i], i, this); | |
} | |
return rv; | |
}; | |
Array.reduce = function(self, fun /*, initial*/) | |
{ | |
if (arguments.length >= 2) | |
{ | |
return Array.prototype.reduce.call(self, fun, arguments[1]); | |
} | |
return Array.prototype.reduce.call(self, fun); | |
}; | |
} | |
if (!Array.prototype.reduceRight) | |
{ | |
Array.prototype.reduceRight = function(fun /*, initial*/) | |
{ | |
var len = this.length; | |
if (typeof fun != "function") | |
throw new TypeError(); | |
// no value to return if no initial value, empty array | |
if (len == 0 && arguments.length == 1) | |
throw new TypeError(); | |
var i = len - 1; | |
if (arguments.length >= 2) | |
{ | |
var rv = arguments[1]; | |
} | |
else | |
{ | |
do | |
{ | |
if (i in this) | |
{ | |
rv = this[i--]; | |
break; | |
} | |
// if array contains no values, no initial value to return | |
if (--i < 0) | |
throw new TypeError(); | |
} | |
while (true); | |
} | |
for (; i >= 0; i--) | |
{ | |
if (i in this) | |
rv = fun.call(null, rv, this[i], i, this); | |
} | |
return rv; | |
}; | |
Array.reduceRight = function(self, fun /*, initial*/) | |
{ | |
if (arguments.length >= 2) | |
{ | |
return Array.prototype.reduceRight.call(self, fun, arguments[1]); | |
} | |
return Array.prototype.reduceRight.call(self, fun); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment