Problem
Writing a polyfill for Array.prototype.reduce in JavaScript is a common frontend interview task because it checks whether you know the method's exact contract, especially the edge cases around the optional initial value.
Implement Array.prototype.myReduce(callback, initialValue) so that it behaves like the native Array.prototype.reduce.
Requirements
callbackis called with(accumulator, currentValue, index, array)for each element, from left to right, and its return value becomes the next accumulator.myReducereturns the final accumulator.- If
initialValueis provided, it is the first accumulator and processing starts at index0. - If
initialValueis omitted, the first element is used as the first accumulator and processing starts at index1. - An explicitly passed
initialValueofundefinedstill counts as provided. - Calling it on an empty array with no
initialValuethrows aTypeError; with aninitialValue, it returns that value without callingcallback. - Throw a
TypeErrorifcallbackis not a function. - Holes in sparse arrays are skipped, just like the native method.
- Do not use the built-in
reduce.
Example
[5, 10, 15].myReduce((acc, n) => acc + n, 100); // 130
[2, 3, 4].myReduce((acc, n) => acc * n); // 24
["a", "b"].myReduce((acc, s, i) => acc + s + i, ""); // "a0b1"
[].myReduce((acc, n) => acc + n, 0); // 0
[].myReduce((acc, n) => acc + n); // TypeError
[1, , 3].myReduce((acc, n) => acc + n); // 4
Follow-ups
- How would you implement
myReduceRight? - Why is extending
Array.prototyperisky in production code?