DEV Community

Discussion on: You don't need Array.reduce()

Collapse
 
seniorjoinu profile image
Alexander • Edited

Seriously, man? for..of?

const myTotalLikes = retrieveAllPosts()
    .filter(p => p.user == me)
    .map(p => p.likes)
    .reduce((acc, like) => acc + like, 0)
Enter fullscreen mode Exit fullscreen mode

Sometimes it's better to use for..of (e.g. when you need some boost iterating over a huge collection you can do all the stuff in one loop) but functional style is much more useful when you are trying to express yourself to your colleagues.

Collapse
 
lewiscowles1986 profile image
Lewis Cowles

My head nearly exploded looking at that. Map reduce is not a good pattern for application engineering, it's a backend big-unstructured-data pattern.

retrievePostsFor(me) would be so much easier to think about as well. Baking in getting all posts and filtering is just not clear unless you have a shallow micro-service code-base, embrace the cascade.

Finally wrap that up in a method

function totalLikes(user) {
    return likes = retrievePostsFor(user)
        .map(p => p.likes)
        .reduce((sum, likes) => sum + likes, 0);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lewiscowles1986 profile image
Lewis Cowles • Edited

to anyone liking this, it works better if you just send in users. Then it doesn't matter where they come from, and anything with 0 likes just adds items to the list...

In-fact it doesn't need to be a user at all. Just something implementing a likeable interface, which has a method to retrieve likes.