Skip to content

Instantly share code, notes, and snippets.

@ronanyeah
Created June 5, 2022 14:17
Show Gist options
  • Save ronanyeah/7c5b418ac4f53dccc02c162407f91e88 to your computer and use it in GitHub Desktop.
Save ronanyeah/7c5b418ac4f53dccc02c162407f91e88 to your computer and use it in GitHub Desktop.
[].reduce vs. [].flatMap
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