Created
December 15, 2009 07:42
-
-
Save twada/256764 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* (c) 2009 Takuto Wada; MIT License | |
* JavaScript 1.8 compliant Array#reduce that also works with old prototype.js | |
* usage: load this AFTER prototype.js | |
*/ | |
(function () { | |
// prototype.js's Array#reduce is removed since 1.6.1_rc2 | |
// see: http://github.com/sstephenson/prototype/commit/b34355653e1a663764fd8f69b4915f966c58cf55 | |
if (typeof Prototype !== 'undefined' && /^1\.(?:[0-5]\.\S+|6\.(?:0(?:\.\d)?|1_rc1))$/.test(Prototype.Version)) { | |
var prototypeJsReduce = Array.prototype.reduce; | |
// using Firefox's reduce implementation. | |
// see: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce | |
Array.prototype.reduce = function(fun /*, initial*/) { | |
// modification: call prototype.js's Array#reduce if no arguments given | |
if (arguments.length == 0) | |
return prototypeJsReduce.call(this); | |
var len = this.length >>> 0; | |
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; | |
var rv; | |
if (arguments.length >= 2) { | |
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; | |
}; | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment