JavaScriptMedium
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
- Validate
thisand the callback (TypeError). - Detect whether an initial value was provided with
arguments.length >= 2, notinitialValue !== undefined.[1, 2].reduce(fn, undefined)must useundefinedas the start. - 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. - Call
callback(accumulator, value, index, array); notereducehas nothisArg. - Skip holes.
- Read
lengthonce.
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`);56 const O = Object(this);7 const len = O.length >>> 0;8 let i = 0;9 let acc;1011 if (arguments.length >= 2) {12 acc = initialValue; // even if it's undefined13 } else {14 while (i < len && !(i in O)) i++; // find the first existing element15 if (i >= len) throw new TypeError("Reduce of empty array with no initial value");16 acc = O[i++];17 }1819 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});2829console.log([1, 2, 3, 4].myReduce((sum, n) => sum + n, 0)); // 1030console.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 }3233// 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|236console.log([1, 2].myReduce(join), [1, 2].reduce(join)); // 1|2 1|23738// Holes are skipped, including when looking for the start39console.log([, , 5, , 6].myReduce((a, b) => a + b)); // 114041// Empty array without an initial value throws, like the native one42try {43 [].myReduce((a, b) => a + b);44} catch (e) {45 console.log(e.message); // Reduce of empty array with no initial value46}4748delete 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.