4 ms·
I tend to try to avoid for loops unless absolutely necessary. I prefer to express operations as various combinations of map, reduce, filter, etc.
by matt-attack 3y ago
I tend to try to avoid for loops unless absolutely necessary. I prefer to express operations as various combinations of map, reduce, filter, etc.
- recursive 3y agoI tend to avoid map and filter unless the code I'm writing can be naturally expressed using them. I almost never use reduce. Sum of a list is one of the few reasonable use cases. I've seen some horrific reduce code that's working very hard to avoid an explicit loop. If I need to count occurrences of each character in a string, I'm using a loop.
- dmix 3y agoIs there a functional rationale for this or more of style thing? I almost never use reduce but I use map and filter (and forEach) everywhere. The syntax of for loops just seems so dirty to me but maybe I just stylistically like the functional / immutable approach to architecting code which is why I use Ramda.
- ghayes 3y agoinput.split('').filter((c) => c === chr).length; Edit: ah I assume you mean more like a histogram. Yeah, that's going to be less clean, e.g. input.split('').reduce((acc, el) => ({...acc, [el]: ( acc[el] ?? 0 ) + 1 }), {});
- recursive 3y agoThis is exactly the type of code I'm talking about. That spread operator is producing a lot of garbage (in the GC sense) for no real reason. It's just to avoid mutation and a loop.