reduce folds a list into one value: a cart into its total, a list of events into counts per type, an array of pairs into an object. It has one rule that trips people up: without an initial value, the first item becomes the starting value, and an empty array then has nothing to start from.
Write Array.prototype.myReduce(callback, initialValue) in reduce.js. It must behave like the built-in Array.prototype.reduce for every case below.
Array.prototype.myReduce=functionmyReduce(callback, initialValue) // returns the last accumulator
callback(accumulator, value, index, array): called for each index the array has, from left to right. What it returns is the accumulator of the next call. array is the object myReduce was called on. The callback's this is undefined: reduce has no thisArg.
initialValue: the starting accumulator. Passing it, even as undefined, is different from leaving it out.
With an initial value, the first call receives it as the accumulator, with the item at index 0.
Without an initial value, the first item that exists is the starting accumulator, and the first call is for the next item that exists. A single item is returned without calling the callback.
Passing undefined as the initial value counts as passing one.
An empty array (or one with only holes) returns the initial value when there is one, and throws a TypeError when there is not.
Holes are skipped, both when looking for the starting item and in the loop. An index that holds undefined is an item.
The callback receives the accumulator, the value, the index and the array, with this undefined. The result is whatever the last call returned, of any type, even undefined.
The original array is not changed. length is read once: items pushed during the call are not visited, and an item deleted before the loop reaches it is skipped.
myReduce works on any object with a length (an array-like object, or a string), called with Array.prototype.myReduce.call(…). length is converted to a whole number from 0 up: "2" is 2, 2.9 is 2, -1 and a missing length are 0. A length that is a BigInt or a Symbol, or an object whose valueOf returns one, throws a TypeError, as the built-in does.
It throws a TypeError when the callback is not a function (after reading length, as the built-in does, but before iterating, even for an empty array with an initial value), and when it is called on null or undefined.
An error thrown by the callback reaches the caller unchanged.
[1, 2, 3, 4].myReduce((sum, value) => sum + value, 0); // 10[1, 2, 3].myReduce((sum, value) => sum + value); // 6: starts from 1, first call is for index 1
Plain JavaScript in a browser page; the tests call Array.prototype.myReduce from reduce.js.
reduce.js starts with "use strict". Keep it: in strict mode, this inside myReduce is exactly the value it was called on, so a call on null can be detected.
Not allowed: the built-in reduce, reduceRight and forEach. The tests delete them from Array.prototype while myReduce runs. Write the loop yourself.