4 ms·
As mentioned in one of the comments, this is nowhere near the definition of functional programming. > It beats complex for-loops Nvm. I still prefer for loops
by twii 9y ago
As mentioned in one of the comments, this is nowhere near the definition of functional programming.
> It beats complex for-loops
Nvm. I still prefer for loops in most cases, in some way it's easier to understand for me if I read it some months later. For example the reduce function I would write something like this:
getPlayersByCountry= ( footballPlayers= [], players= {} ) ->
for player in footballPlayers
if players.hasOwnProperty player.country
players[ player.country ].push player
return players
playersByCountry= getPlayersByCountry footballPlayers, {France: [], England: [], Spain: []}
I guess it's mere a matter of taste.
- seanwilson 9y agoWhat I mean is when you have a 200 line for loop that includes other for loops, "continue" statements, if statements and modifying state it gets really confusing quickly. If it's short it's probably going to be OK to understand anyway but if you can decompose a long for loop into several map, reduces and filters it's much easy to understand what's going on because it's more linear. For that example, you should really have a generic "group by" function to use anyway that plays nice with your map, filter and reduce functions.
- louthy 9y agoEven with a small loop like that there are potential problems. Should there be an 'else'? You might know because you wrote it, but the compiler/runtime doesn't, and neither do other programmers on your team without taking time to analyse your intention. Using map/reduce/filter/etc. is declarative and less likely to result in spurious errors. That's the benefit of this declarative approach, it removes the relentless boilerplate, works solely with intent, and reduces cyclomatic complexity.
- deleted 9y ago[deleted]