Implement a Polyfill for Array.prototype.reduce

Problem Write a spec-faithful polyfill for Array.prototype.reduce.

Input / Output

  • myReduce(callback, initialValue?) on an array; callback(accumulator, current, index, array).

Constraints

  • Must match native semantics: no initialValue → accumulator seeds from the FIRST PRESENT element and iteration starts at the next; empty array with no initialValue → TypeError; holes in sparse arrays are skipped; the callback must not be called for the seed element.

Example

  • [1,2,3].myReduce((a,b) => a+b) → 6 (callback runs twice, not three times).
  • [].myReduce(f) → TypeError; [].myReduce(f, 0) → 0 (callback never runs).
asked …
LeaderboardSalaryAccount