FrontendInterviews.dev

Loading problem…

72. Array.prototype.reduce (Polyfill)

Medium•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

Implement Array.prototype.myReduce — a polyfill that behaves like native Array.prototype.reduce.

Reduce applies a reducer function to each element and returns a single accumulated result.

Requirements

1) Core behavior

  • Signature: arr.myReduce(callbackFn, initialValue?)
  • Callback receives: (accumulator, currentValue, index, array)
  • Return the final accumulator.

2) initialValue rules (most important)

  • If initialValue is provided: start at index 0 with that accumulator.
  • If initialValue is not provided:
  • Find the first existing element and use it as accumulator.
  • Start reducing from the next index.

3) Edge cases

  • If the array has no existing elements and no initialValue, throw TypeError.
  • Skip holes in sparse arrays.
  • Capture length at start (pushes beyond initial length are not visited).

Constraints

  • Must not use native reduce internally.
  • callbackFn must be a function; otherwise throw TypeError.
  • Must follow initialValue semantics exactly.
  • If no initialValue and no existing elements -> throw TypeError.
  • Skip holes in sparse arrays.
  • Capture length at start; items pushed beyond original length are not visited.