Last active
March 25, 2022 22:23
-
-
Save juniorbird/f0ca46c1d23f0dc0d66081102b359e62 to your computer and use it in GitHub Desktop.
A simple implementation of Reduce in Javascript
This file contains hidden or 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
'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