3 ms·
The problem with these utility functions is that they're not chainable. It would also be nice if they made more use of Array.map or reduce rather than using for
by petre 4y ago
The problem with these utility functions is that they're not chainable. It would also be nice if they made more use of Array.map or reduce rather than using for loops and mutating things. If I couldn't do it using a simple Array.map, reduce, filter or sort, I'd still use loadash or underscore if it was loaded.
- afavour 4y agoI'm curious why? It's my understanding things like for loops are used for performance reasons, which makes sense: running .map().reduce().filter() involves creating three separate arrays which can be a drag if you're dealing with a large array. For loops don't have that issue (and more broadly a utility library like lodash surely ought to prioritize performance over code readability)
- petre 4y agoNot what I meant, as one can obviously also filter or map in a reduce block, but maybe one needs to do a sort afterwards.
- afavour 4y ago> one can obviously also filter or map in a reduce block Sure but you can't filter in a map, or map in a filter.
- leipert 4y agoReason why I like flatMap. It’s like map with a simple shortcut for filtering.
- dpkirchner 4y agoYou can filter in a compactMap (called just compact in lodash, apparently), FWIW. Not that this negates your point.
- dragonwriter 4y agosure. Reduce is the generic array -> anything operation, flatMap is the generic array -> array operation (and, as such, a special case of reduce), and map and filter are specialized array -> array operations (and, as such, special cases of flatMap and, transitively, of reduce.) So you can do both map and filter as part of a reduce or flatMap, but not either as part of the other. (You may be able to get close by doing ugly things in a map/filter that abuses the second and third arguments, but I don't think you can get a general map out of filter or vice versa, and you shouldn't do the kind of things you'd need to do to get close, just use flatMap.)