Skip to content
Onsite

Array.prototype.reduce Polyfill

EasyP1Coding

Implement myReduce, a polyfill for Array.prototype.reduce.

myReduce is called with the array as this: myReduce.call(arr, callback, initialValue). The callback is callback(acc, value, index, arr).

Rules that match the real method:

  • If initialValue is passed (even as undefined), start with it at index 0.
  • If it is not passed, start with the first existing element as the accumulator and begin at the next index.
  • Reducing an empty array without an initial value throws a TypeError.
  • Holes are skipped. A non-function callback throws a TypeError.

Example 1

Input
myReduce.call([1, 2, 3], (a, x) => a + x, 0)
Output
6

Example 2

Input
myReduce.call([1, 2, 3], (a, x) => a + x)
Output
6
Why
No initial value: the accumulator starts as 1 and the callback runs for 2 and 3.

Constraints

  • 0 <= array length <= 10^5
  • Detect a missing initial value with arguments.length, not with === undefined.

Hints

Run checks the 3 visible tests, Submit all 9.