Exercise 19: Promise Reduce (async accumulator)
Problem Statement
Function `promiseReduce(arr, fn, initial)` banao jo array ko async reducer se reduce kare.
Example: promiseReduce([1,2,3], async (acc, x) => acc + x, 0)
Sample Output:
await promiseReduce([1,2,3], async (acc, x) => acc + x, 0) => 6 // Reduces with async accumulator
Solution
const promiseReduce = async (arr, fn, initial) => {
let acc = initial;
for (const item of arr) acc = await fn(acc, item);
return acc;
};Explanation
Overall Goal:
- Array ko async reducer se reduce karna.
Real world:
- Data aggregation: async reduction.
- Sequential processing: async accumulation.