Exercise 14: Higher-Order Function: Reduce Implementation
Problem Statement
Create a function `myReduce(arr, fn, initial)` that is a custom implementation of array.reduce().
Sample Output:
myReduce([1, 2, 3], (acc, x) => acc + x, 0) => 6 myReduce([1, 2, 3], (acc, x) => acc + x) => 6
Solution
const myReduce = (arr, fn, initial) => {
let acc = initial;
let start = 0;
if (initial === undefined && arr.length > 0) {
acc = arr[0];
start = 1;
}
for (let i = start; i < arr.length; i++) acc = fn(acc, arr[i], i, arr);
return acc;
};Explanation
Overall Goal:
- Array.reduce() ka custom implementation.
Real world:
- Understanding: how reduce works.
- Custom reduction: modified behavior.