Thanks for your comment! I disagree about scan/mash though.
It's a good practice, in my opinion, to extract such logic to dedicated functions. For one thing, it reduces code duplication: If you wanted to use this logic in several places, you'd otherwise have the same reducer code repeated over and over again. It also makes the meaning more clear when a function is given a name. Spreading a lot of anonymous lambdas through the code makes it harder to understand. Finally, using a dedicated function means we can optimize that function for performance later on if we need to.
You can see that the sample implementations of scan and mash I provided are just thin wrappers around reduce - so there is not really a big difference.
I recommend using named functions even for very simple cases where it is arguably not a big deal. For instance, I think sum([1,2,3]) is better than [1,2,3].reduce((acc, item)=>acc+item) .
Oh, well. Yes, you are right. What I wrote I meant it, just as a demonstration exercise, it might be over-engineered. But if it is a method that needs to be used multiple times across a code base, then yes, by all means, wrap it in a function to make it easier to re-use. There are indeed plenty of cases where reduce can help to build functions like smash or scan.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Thanks for your comment! I disagree about scan/mash though.
It's a good practice, in my opinion, to extract such logic to dedicated functions. For one thing, it reduces code duplication: If you wanted to use this logic in several places, you'd otherwise have the same reducer code repeated over and over again. It also makes the meaning more clear when a function is given a name. Spreading a lot of anonymous lambdas through the code makes it harder to understand. Finally, using a dedicated function means we can optimize that function for performance later on if we need to.
You can see that the sample implementations of
scanandmashI provided are just thin wrappers around reduce - so there is not really a big difference.I recommend using named functions even for very simple cases where it is arguably not a big deal. For instance, I think
sum([1,2,3])is better than[1,2,3].reduce((acc, item)=>acc+item).Oh, well. Yes, you are right. What I wrote I meant it, just as a demonstration exercise, it might be over-engineered. But if it is a method that needs to be used multiple times across a code base, then yes, by all means, wrap it in a function to make it easier to re-use. There are indeed plenty of cases where reduce can help to build functions like smash or scan.