Create a polyfill for reduce()

A reduce polyfill keeps an accumulator: it starts from initialValue if one is passed (checked with arguments.length, since undefined is a valid initial value), otherwise from the first existing element; it then calls the reducer for each remaining existing element and returns the final accumulator.

Spec details that separate good answers from great ones

  1. Validate this and the callback (TypeError).
  2. Detect whether an initial value was provided with arguments.length >= 2, not initialValue !== undefined. [1, 2].reduce(fn, undefined) must use undefined as the start.
  3. Without an initial value, find the first existing index (skipping holes) as the start. If there is none (empty or all holes), throw TypeError: Reduce of empty array with no initial value.
  4. Call callback(accumulator, value, index, array); note reduce has no thisArg.
  5. Skip holes.
  6. Read length once.

reduceRight

The same algorithm iterating from the end; a natural follow-up.

Complexity

O(n) time, O(1) extra space (plus whatever the accumulator holds).

Code example

js
1Object.defineProperty(Array.prototype, "myReduce", {
2 value: function myReduce(callback, initialValue) {
3 if (this == null) throw new TypeError("Array.prototype.myReduce called on null or undefined");
4 if (typeof callback !== "function") throw new TypeError(`${callback} is not a function`);
5
6 const O = Object(this);
7 const len = O.length >>> 0;
8 let i = 0;
9 let acc;
10
11 if (arguments.length >= 2) {
12 acc = initialValue; // even if it's undefined
13 } else {
14 while (i < len && !(i in O)) i++; // find the first existing element
15 if (i >= len) throw new TypeError("Reduce of empty array with no initial value");
16 acc = O[i++];
17 }
18
19 for (; i < len; i++) {
20 if (i in O) acc = callback(acc, O[i], i, O);
21 }
22 return acc;
23 },
24 writable: true,
25 configurable: true,
26 enumerable: false,
27});
28
29console.log([1, 2, 3, 4].myReduce((sum, n) => sum + n, 0)); // 10
30console.log([1, 2, 3, 4].myReduce((sum, n) => sum + n)); // 10 (starts from the first element)
31console.log(["a", "b"].myReduce((acc, x, i) => ({ ...acc, [x]: i }), {})); // { a: 0, b: 1 }
32
33// undefined is a valid initial value (detected with arguments.length, not !== undefined)
34const join = (acc, x) => [acc, x].join("|");
35console.log([1, 2].myReduce(join, undefined), [1, 2].reduce(join, undefined)); // |1|2 |1|2
36console.log([1, 2].myReduce(join), [1, 2].reduce(join)); // 1|2 1|2
37
38// Holes are skipped, including when looking for the start
39console.log([, , 5, , 6].myReduce((a, b) => a + b)); // 11
40
41// Empty array without an initial value throws, like the native one
42try {
43 [].myReduce((a, b) => a + b);
44} catch (e) {
45 console.log(e.message); // Reduce of empty array with no initial value
46}
47
48delete Array.prototype.myReduce;

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app