Last active
August 29, 2015 14:16
-
-
Save ruemic/4cb049ef658228e78909 to your computer and use it in GitHub Desktop.
Notes about the Array.prototype.reduce polyfill
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
if (!Array.prototype.reduce) { | |
Array.prototype.reduce = function(callback /*, initialcurrentValue*/) { | |
'use strict'; | |
// Check if calling on array | |
if (this == null) { | |
throw new TypeError('Array.prototype.reduce called on null or undefined'); | |
} | |
// Check if callback function is supplied | |
if (typeof callback !== 'function') { | |
throw new TypeError(callback + ' is not a function'); | |
} | |
// Init some variables | |
var array = Object(this), | |
length = array.length >>> 0, | |
index = 0, | |
currentValue; | |
// Basically we need to figure out the current value, aka the 'accumulator' | |
// If there's an init arg, set it as the current value | |
if (arguments.length == 2) { | |
currentValue = arguments[1]; | |
} else { | |
// Increment the index until it represents a value in the array (in case it doesn't already) | |
while (index < length && ! index in array) { | |
index++; | |
} | |
// Check if there's actually an array/index we can use | |
if (index >= length) { | |
throw new TypeError('Reduce of empty array with no initial currentValue'); | |
} | |
// Set the current value to 1st item of array and increment the index | |
currentValue = array[index++]; | |
} | |
// Great we've done our due diligence and we're ready to do some recursion! | |
// Invoke the callback function for each item in the array | |
for (; index < length; index++) { | |
if (index in array) { | |
// Update the accumulator with the return value of the callback. | |
// Notice we pass in the current value as the 'previousValue' argument | |
// and use the next item in the array as the 'currentValue' argument. | |
currentValue = callback(currentValue, array[index], index, array); | |
} | |
} | |
return currentValue; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment