Last active
August 3, 2018 16:36
-
-
Save Cornpop456/1383a2726018216be7f3481b698c9547 to your computer and use it in GitHub Desktop.
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(array, fn, initial) { | |
if (!(array instanceof Array)) { | |
throw new TypeError('Illegal first argument, (not an array)'); | |
} else if (!(fn instanceof Function)) { | |
throw new TypeError('Illegal second argument, (not a function)'); | |
} | |
let startIndex = 1, | |
current = array[0]; | |
if (initial) { | |
startIndex = 0; | |
current = initial; | |
} | |
for (let i = startIndex; i < array.length; i++) { | |
current = fn(current, array[i], i, array); | |
} | |
return current; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment