DEV Community

Discussion on: The case for reducers

Collapse
 
tiagojpdias profile image
Tiago Dias • Edited

Hey, and first of all thanks for putting effort on your post. I hope it doesn't get lost in the flood of low quality ones...

Regarding your article I just want to point out that the first two examples, despite being doable with a .reduce(), in my opinion they're way complex. We can achieve the same by doing something like:

// Pretend these are complex objects
const posts = [
    { tags: ["javascript", "discuss"] },
    { tags: ["javascript", "react", "vue-is-better"] },
    { tags: ["discuss"] },
    { tags: ["javascript"] },
];

// const allTags = posts.map(post => post.tags).flat();
const allTags = posts.map(({ tags }) => tags).flat();
const allUniqueTags = new Set(allTags);

console.log(allUniqueTags); // Set(4) { 'javascript', 'discuss', 'react', 'vue-is-better' }

Enter fullscreen mode Exit fullscreen mode
const posts = [
    { category: "javascript", tags: ["javascript", "discuss"] },
    { category: "frameworks", tags: ["javascript", "react", "vue-is-better"] },
    { category: "watercooler", tags: ["discuss"] },
    { category: "functional programming", tags: ["javascript"] },
];

// const capitalize = (word) => word[0].toUpperCase() + word.slice(1); 
const capitalize = ([initial, ...rest]) => initial.toUpperCase() + rest.join(''); 

// const discussable = posts.filter(post => post.tags.includes('discuss'));
const discussable = posts.filter(({ tags }) => tags.includes('discuss'));

// const capitalizedCategories = discussable.map(post => capitalize(post.category));
const capitalizedCategories = discussable.map(({ category }) => capitalize(category));

console.log(capitalizedCategories); // [ 'Javascript', 'Watercooler' ]
Enter fullscreen mode Exit fullscreen mode

Regarding the pipe, that is the perfect use case for the reduce() !
Nice job explaining it.

I just wanted to bring more viable options to achieve the same outcome, not to undermine your examples.

Thanks once again!

Collapse
 
vonheikemen profile image
Heiker

Thanks for the kind words.


About those examples I made in the post, interestingly enough they could also be done using Array.flatMap.

  • Unique tags
new Set(posts.flatMap(({ tags }) => tags))
Enter fullscreen mode Exit fullscreen mode
  • FilterMap
posts.flatMap(({ tags, category }) =>
  tags.includes('discuss')
    ? capitalize(category)
    : []
);
Enter fullscreen mode Exit fullscreen mode