how not to use reduce

YCM Jason - Jun 30 '20 - - Dev Community

Why not reduce?

This list intend to be a forever growing one that hope to collect typical patterns of reduce to avoid. Please feel free to suggest more examples!


This post is not about space / time performance perks by not using reduce. This is all about readability.


🔴 Do not

faces.reduce((acc, face) => {
  return [...acc, mask(face)]
}, [])
Enter fullscreen mode Exit fullscreen mode

✅ Do

faces.map(mask)
Enter fullscreen mode Exit fullscreen mode

🔴 Do not

bags.reduce((acc, bag) => {
  return [...acc, ...bag.apples]
}, [])
Enter fullscreen mode Exit fullscreen mode

✅ Do

bags.flatMap(bag => bag.apples)
Enter fullscreen mode Exit fullscreen mode

🔴 Do not

phones.reduce((acc, phone) => {
  return isNew(phone) ? [...acc, phone] : acc
}, [])
Enter fullscreen mode Exit fullscreen mode

✅ Do

phones.filter(isNew)
Enter fullscreen mode Exit fullscreen mode

🔴 Do not

dogs.reduce((acc, dog) => {
  return isHappy(dog) ? acc + 1 : acc
}, 0)
Enter fullscreen mode Exit fullscreen mode

✅ Do

dogs.filter(isHappy).length
Enter fullscreen mode Exit fullscreen mode

🔴 Do not

people.reduce((acc, person) => ({
  [person.dna]: person
}), {})
Enter fullscreen mode Exit fullscreen mode

✅ Do

Object.fromEntries(
  people.map(person => [person.dna, person])
)
Enter fullscreen mode Exit fullscreen mode

🔴 Do not

people.reduce((acc, person) => {
  return Math.max(acc, person.age)
}, -Infinity)
Enter fullscreen mode Exit fullscreen mode

✅ Do

Math.max(...people.map(person => person.age))
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player