Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created February 28, 2014 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bloodyowl/9274271 to your computer and use it in GitHub Desktop.
Save bloodyowl/9274271 to your computer and use it in GitHub Desktop.
polyfill.io? meh
// https://github.com/jonathantneal/polyfill/blob/master/source/Array.prototype.reduce.js
// Array.prototype.reduce
Array.prototype.reduce = function reduce(callback, initialValue) {
var array = this, previousValue = initialValue || 0;
for (var index = 0, length = array.length; index < length; ++index) {
previousValue = callback.call(window, previousValue, array[index], index, array);
}
return previousValue;
};
"use strict"
// http://es5.github.io/#x15.4.4.21
var FUNCTION_CLASS = "[object Function]"
, STRING_CLASS = "[object String]"
, supportsStringAccess = "x"[0] == "x"
, _toString = {}.toString
, toObject = function(value){
if(value == null) {
throw new TypeError("'" + String(value) + "' is not an object")
}
if(!supportsStringAccess && value && _toString.call(value) == STRING_CLASS) {
return value.split("")
}
return new Object(value)
}
Array.prototype.reduce = function(fn){
var array = toObject(this)
, index = -1
, length = array.length >>> 0
, accummulator
, hasInitialValue
, reduced
, item
if(_toString.call(fn) != FUNCTION_CLASS) {
throw new TypeError()
}
if(arguments.length > 1) {
accummulator = arguments[1]
} else {
hasInitialValue = false
while(++index < length) {
if(!(hasInitialValue = index in array)) {
continue
}
accummulator = array[index]
break
}
if(!hasInitialValue) {
throw new TypeError()
}
}
while(++index < length) {
if(!(index in array)) continue
accummulator = fn.call(void 0, accummulator, array[index], index, array)
}
return accummulator
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment