call(back)
FrontendmediumSign in to star problems

Implement Array.prototype.reduce

Write Array.prototype.myReduce(cb, initial) so it matches the built-in reduce. The grader disables the native map, filter, reduce and concat while your code runs.

Rules

  • Call cb(accumulator, value, index, array) for each element, skipping holes. A callback that isn't a function throws TypeError.
  • Use initial whenever that argument was passed, even as undefined. Otherwise start from the first element that exists and continue after it.
  • With no initial value and nothing to reduce, throw TypeError.
  • Define the method with function, not an arrow, so this is the array.
[1, 2, 3].myReduce((a, v) => a + v, 10)         // 16
[1, 2].myReduce((a, v) => String(a) + v, undefined)   // "undefined12"

Tests write a hole as "<hole>"; the grader turns it into a real empty slot. Callbacks are named in each test's input and supplied by the grader.

Hints

Hint 1

A default parameter can't carry the initial value, because reduce(fn, undefined) must count as supplied. Take ...rest and check rest.length.

Hint 2

Without an initial value, skip leading holes to find the first real element; if there is none, throw TypeError.

Asked at