Skip to content

Instantly share code, notes, and snippets.

@juniorbird
Last active March 25, 2022 22:23
Show Gist options
  • Save juniorbird/f0ca46c1d23f0dc0d66081102b359e62 to your computer and use it in GitHub Desktop.
Save juniorbird/f0ca46c1d23f0dc0d66081102b359e62 to your computer and use it in GitHub Desktop.
A simple implementation of Reduce in Javascript
'use strict';
function reducer(array, callback, initializer) {
let accumulator = (initializer === undefined) ? 0 : initializer;
for (let i = 0; i < array.length; i++) {
accumulator = callback(accumulator, array[i]);
}
return accumulator;
}
const arr = [2, 3, 4];
const sum = (a, b) => a + b;
console.log(reducer(arr, sum, 1)); // logs 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment