Skip to content

Instantly share code, notes, and snippets.

@Cornpop456
Last active August 3, 2018 16:36
Show Gist options
  • Save Cornpop456/1383a2726018216be7f3481b698c9547 to your computer and use it in GitHub Desktop.
Save Cornpop456/1383a2726018216be7f3481b698c9547 to your computer and use it in GitHub Desktop.
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