Created
June 5, 2022 14:17
-
-
Save ronanyeah/7c5b418ac4f53dccc02c162407f91e88 to your computer and use it in GitHub Desktop.
[].reduce vs. [].flatMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const xs = [...Array(10000).keys()]; | |
const prom = (n) => Promise.resolve(n); | |
(async () => { | |
console.time("reduce"); | |
const t1 = xs.reduce( | |
(memo, n) => (n % 2 === 0 ? [...memo, prom(n)] : memo), | |
[] | |
); | |
await Promise.all(t1); | |
console.timeEnd("reduce"); | |
console.time("flatMap"); | |
const t2 = xs.flatMap((n) => (n % 2 === 0 ? [prom(n)] : [])); | |
await Promise.all(t2); | |
console.timeEnd("flatMap"); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment