Created
April 25, 2017 08:55
-
-
Save shahbazsyed/768606cb819a312ca69a57bbab0b0192 to your computer and use it in GitHub Desktop.
Functional programming in Js - Reduce
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
Array.prototype.reduce = function(combiner, initialValue) { | |
var counter, accumulatedValue; | |
// If the array to be reduced is empty, then do nothing | |
if (this.length === 0) { | |
return this; //this refers to the Array being reduced | |
} else { | |
/* | |
If the user did not pass an initialValue, that is if the number of arguments passed to the reduce function is just 1, | |
then use the first item from the array as the accumulatedValue to begin with | |
*/ | |
if (arguments.length === 1) { | |
counter = 1; // this makes the second element of the array the currentValue in the combiner function | |
accumulatedValue = this[0]; // this makes the first element the accumulatedValue in the combiner function | |
} else if (arguments.length === 2) { | |
counter = 0; // this makes the first element the currentValue, because the user has provided an initialValue to begin with as the accumulatedValue | |
accumulatedValue = initialValue; | |
} else { | |
throw "Invalid arguments passed to reduce"; | |
} | |
/* | |
Loop through the array, reading the current value and the result of the previous computation back into the combiner function, | |
until we have exhausted the entire array | |
*/ | |
while (counter < this.length) { | |
accumulatedValue = combiner(accumulatedValue, this[counter]); | |
counter++; | |
} | |
// return the final value accumulated, after exhausting the list | |
return [accumulatedValue]; | |
} | |
}; | |
console.log([1, 2, 3].reduce(function(acValue, currValue) { | |
return acValue + currValue; | |
}, 10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment