DEV Community

Discussion on: Is reduce() bad?

Collapse
 
aendra profile image
Ændra Rininsland • Edited

There's been so much .reduce() bashing on Twitter in recent days, it's really annoying given how useful and powerful a method it is.

For instance, you can rate limit a bunch of fetch() requests using async/await and .reduce() in a one-liner like so:

(async () => {
  const listOfUrls = ['https://some-api/endpoint/1', 'https://some-api/endpoint/2', 'https://some-api/endpoint/3'];

  const data = listOfUrls.reduce(
     async (acc, cur) => [...await acc, await fetch(cur).then(r => r.json())], Promise.resolve([]));
})();
Enter fullscreen mode Exit fullscreen mode

(I think; it's been awhile since I wrote one of those)

Granted, with async iterators you can do the following too now:

const listOfUrls = ['https://some-api/endpoint/1', 'https://some-api/endpoint/2', 'https://some-api/endpoint/3'];
const data = [];
(async () => {
  for (const url in listOfUrls) {
    data.push(await fetch(url).then(r => r.json()));
  }
})();
Enter fullscreen mode Exit fullscreen mode

...Or even:

const listOfUrls = ['https://some-api/endpoint/1', 'https://some-api/endpoint/2', 'https://some-api/endpoint/3'];
const data = [];
(async () => {
  const requests = listOfUrls.map(url => fetch(url).then(r => r.json());
  for await (const datum in requests) {
    data.push(datum);
  }
})();
Enter fullscreen mode Exit fullscreen mode

...But those are longer, not much more readable, invoke newer ES functionality that other people in your team might be not familiar with and use mutative array methods.

Collapse
 
kenbellows profile image
Ken Bellows

I don't know, IMO the for loop versions you wrote are far more readable than the reduce version. I typically find that to be true of for vs reduce, which is I think the point of these arguments.

(Unimportant pedantic nitpick: I think you meant to write for ... of rather than for ... in, since in loops over keys rather than values.)

Collapse
 
aendra profile image
Ændra Rininsland

That's fair! TBTH I'm sort of coming back around on using for loops over .reduce(), async iterators are really nice to use for request throttling and flow control, last project I used them in I was a bit taken aback by how intuitive they felt to use once I got into it (I've never been a huge fan of generators but I'm starting to see their value more now after that).

And yes, I definitely meant for ... of — I get that wrong so often! 😅

Thread Thread
 
kenbellows profile image
Ken Bellows

And yes, I definitely meant for ... of — I get that wrong so often! 😅

Ha, same! Especially if I've been writing Python recently, since Python's loop syntax is for x in arr: ...