Created
July 20, 2021 10:36
-
-
Save KoryNunn/cc4bbf1bf7c1f08d4b7e568d893b2271 to your computer and use it in GitHub Desktop.
Array.reduce
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
/* | |
For each item in the array, | |
pass the item into a function with the last value returned from the function. | |
If it's the first item, pass the second parameter (starting value) to reduce in. | |
If no starting value is passed, use the first item in the array, and skip to the second. | |
If no staring value is passed, and the array is empty, throw an error. | |
*/ | |
function reduce(yourFunction, startingValue) { | |
var items = this; | |
var hasStartingValue = arguments.length === 2; | |
var currentResult = startingValue; | |
if (hasStartingValue) { | |
currentResult = startingValue; | |
} else { | |
if(!items.length) { | |
throw 'Reduce of empty array with no initial value'; | |
} | |
currentResult = items[0]; | |
} | |
for (var i = hasStartingValue ? 0 : 1; i < items.length; i++) { | |
currentResult = yourFunction(currentResult, items[i]); | |
} | |
return currentResult; | |
} | |
Array.prototype.reduce = reduce; | |
var output = [1, 2, 3].reduce((lastResult, nextItem) => { | |
var newCurrentResult = lastResult + nextItem; | |
return newCurrentResult; | |
}); | |
console.log(output); // -> 1 + 2 + 3 == 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment