Implement myReduce(arr, callback, initialValue)
The trickiest of the array polyfills, because initialValue is optional, and "omitted" is different from "passed as undefined":
- If
initialValuewas passed (3 arguments), start the accumulator there and iterate over every element from index0. - If it was not passed (2 arguments), use
arr[0]as the initial accumulator and iterate from index1. - If it was not passed and the array is empty, throw a
TypeError.
myReduce([1, 2, 3], (acc, n) => acc + n, 0); // 6
myReduce([1, 2, 3], (acc, n) => acc + n); // 6 (starts from arr[0])
myReduce([], (acc, n) => acc + n); // throws TypeErrorHint: arguments.length (this must be a regular function, not an arrow function) tells you whether the caller actually passed a third argument.