Write Your Own Reduce
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write myReduce(items, fn, initial) without using the built-in reduce or reduceRight. It calls fn(accumulator, item, index, items) for each item in order, feeds each result in as the next accumulator, and returns the last one. With an initial value, the accumulator starts as initial and fn is first called for index 0. Without one, the first item is the starting accumulator and fn is first called for index 1. Passing undefined as initial still counts as giving one. On an empty array, return initial if one was given, and throw a TypeError if not. Don't change items.
Your code must pass
- Combines the items starting from the initial value
- Starts from the first item when there's no initial value
- Passes the accumulator, item, index and array to fn
- Treats an initial value of undefined as given
- Returns initial for an empty array, or throws a TypeError without one
- Works without the built-in reduce