/* Array.prototype.reduce() The reduce() method executes a reducer function (callback) on each element of the array, resulting in a single output value. Syntax: * the reducer function takes in four four arguments, namely Accumulator, curren value, current index, & source array. * in absence of an initial value, the first value of the array is used as the starting point for reduce function Sample signatures: reduce(reducerFn) reduce(reducerFn, initialValue) reduce(function reducerFn(accumulator, currentValue) { ... }) reduce(function reducerFn(accumulator, currentValue, index) { ... }) reduce(function reducerFn(accumulator, currentValue, index, array){ ... }) reduce(function reducerFn(accumulator, currentValue, index, array) { ... }, initialValue) */ // Custom Polyfill Array.prototype.customReduce = function(callback, initialValue) { var accumulator = intialValue === undefined ? undefined : intialValue; for (var i = 0; i < this.length; i++) { if (accumulator !== undefined) accumulator = callback.call(undefined, accumulator, this[i], i, this); else accumulator = this[i]; } return accumulator; } // Proper Polyfill with error handling Array.prototype.betterReduce = function(callback /*, intialVlaue */) { if (this == null) throw new TypeError('betterReduce called on null or not defined'); if (typeof callback !== 'function') throw new TypeError('callback is not a function '); var Obj = this; var len = this.length; var counter = 0; var value; if (arguments.length >= 2) value = arguments[1]; while (counter < len) { value = callback(value, this[counter], counter, this); } return value; }