Last active
January 13, 2020 21:41
-
-
Save bryzettler/cc9e0d00df78f65ff5479d0daeb96ad8 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
// Takes an `array` a `callback` and an `initialValue` | |
// uses an inner `recursiveFn` to iterate over all array values | |
// calling the `callback` on each one | |
const reduce = (orgArray, callback, initialValue) => ( | |
(function recursiveFn(idx, acc) { | |
// base condition to end looping | |
if (idx > orgArray.length - 1) return acc; | |
// calculate and pass values to next step | |
return recursiveFn(idx + 1, callback(acc, orgArray[idx], idx, orgArray)) | |
// start the iterations at orgArray[0] | |
// with (initialValue or array[0]) as the acc | |
})(0, (initialValue || orgArray[0])) | |
); | |
// Basic sum of an array | |
// No `initialValue` supplied so starts with Array[0] | |
reduce([0,1,2,3], (acc, item) => acc + item); | |
// => 10; | |
// Add 1 to all items in array | |
// callback is using es6 to destructure acc into a new array | |
recuce([0,1,2,3], (acc, item) => { | |
acc.push(item + 1); | |
return acc; | |
}, []) // initialValue is [] // acc === [] => true | |
// => [1,2,3,4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment