January 2020
Intermediate to advanced
470 pages
11h 13m
English
Earlier in this chapter, we saw how reduce() could be used to implement reduceRight(). Now let's see how reduce() can also be used to provide a polyfill for map() (not that you will need it, because browsers usually provide both methods, but just to get more of an idea of what you can achieve with these tools).
Our own myMap() is a one-liner, but it can be hard to understand. The idea is that we apply the function to each element of the array and we concat() the result to (an initially empty) result array. When the loop finishes working with the input array, the result array will have the desired output values:
const myMap = (arr, fn) => arr.reduce((x, y) => x.concat(fn(y)), []);
Let's test this with an array ...
Read now
Unlock full access