Skip to content

Instantly share code, notes, and snippets.

@frankstepanski
Created January 30, 2021 01:34
Show Gist options
  • Save frankstepanski/ff2766744fa40db0d2128f8b4d034a73 to your computer and use it in GitHub Desktop.
Save frankstepanski/ff2766744fa40db0d2128f8b4d034a73 to your computer and use it in GitHub Desktop.
Reproducing the reduce() method
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