Skip to content

Instantly share code, notes, and snippets.

@ilanl
Created March 31, 2020 11:35
Show Gist options
  • Save ilanl/8ee4d7673c0a8553a65fde1b1d384906 to your computer and use it in GitHub Desktop.
Save ilanl/8ee4d7673c0a8553a65fde1b1d384906 to your computer and use it in GitHub Desktop.
function reduce(arr, reduceCallback, initialValue) {
if (!Array.isArray(arr) || !arr.length || typeof reduceCallback !== 'function')
{
return [];
} else {
let hasInitialValue = initialValue !== undefined;
let value = hasInitialValue ? initialValue : arr[0];
for (let i = hasInitialValue ? 0 : 1, len = arr.length; i < len; i++) {
value = reduceCallback(value, arr[i], i, arr);
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment