Back To Basics - Hand Implementing Reduce
Other times, I’ll ask more general questions like hand implement a reduce.
- Ken Wheeler 4/23/20
Lately I've noticed a lot of devs on Twitter talking about hand implementing native JavaScript functions. It got me thinking, sure I know the principles of what Reduce does but how well do I really understand what's going on under the hood. I'm sure like most devs, I go straight for the example section of the docs and go from there. No time like the present though to really get a detailed look and really understand what's going on.
Implementing Reduce
const reduce = (array, cb, acc) => {
for (let i = 0; i <= array.length; i++) {
if (!acc) {
acc = array[i]
} else {
acc = cb(acc, array[i], i, array)
}
}
return acc;
}
So in english whats going on.
- 1: Loop over array
- 2: If we pass in an initial value, invoke the CB. Else assign accumulator to the value of the first item of the array.
- 3: Subsequent calls, we re-assign the accumulator by invoking the callback function.
- 4: Return the accumulator
Note: The callback function accepts 4 arguments. The last two, the index current index and the source array are optional.
Example implementation
Here we want to get the sum of numbers in an array.
const nums = [0,1,2,3,4]
const getSum = reduce(nums, (acc, val, _, __) => {
return acc + val;
}, 0) // result = 10