Created
January 30, 2021 01:34
-
-
Save frankstepanski/ff2766744fa40db0d2128f8b4d034a73 to your computer and use it in GitHub Desktop.
Reproducing the reduce() method
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
function reduce(arr, callbackFunc, initVal) { | |
/* | |
1. make sure array is being passed | |
2. if initVal is not passed, accumulator uses the first element in array | |
then just use the array starting with 2nd element | |
if initVal is passed, accumulator is set to initVal | |
*/ | |
if (Array.isArray(arr)) { | |
let accum; | |
if (initVal === undefined) { | |
accum = arr[0]; | |
arr = arr.slice(1); | |
} else { | |
accum = initVal; | |
} | |
for (let i = 0; i < arr.length; i++) { | |
accum = callbackFunc(accum, arr[i], i, arr); | |
} | |
return accum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment