Skip to the solution
MediumFrontendAsked in 20246 min read

Async reduce utility

1.0k views

The problem

Problem, as an interviewer would state it: "Implement reduceAsync(array, reducer, initial) — like Array.prototype.reduce, but the reducer function returns a promise, and each step must genuinely wait for the previous one before starting."

Examples:

Code
await reduceAsync([1, 2, 3], async (acc, n) => acc + n, 0); // 6, computed sequentially

Clarifying questions expected:

  • Must this genuinely run sequentially (each step awaiting the previous), or would running reducer calls concurrently and combining results differently be acceptable?
  • What should happen with an empty array and an explicit initial value?
  • Should the reducer also receive the index and the original array, matching the real synchronous reduce signature?

Code / implementation expected: Yes — real, direct proof that the accumulator is correctly threaded through each step in strict sequential order, verified via a real, logged execution order.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: reduceAsync() produces the correct accumulated result and is verified genuinely sequential via a real logged execution order

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 92 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

Implement compose() and pipe() for function composition

Continue