4 ms·
> This pattern is nothing really special and I should have realized it sooner but I found myself filtering a collection of items to get all items that matched a
by seanwilson 7y ago
> This pattern is nothing really special and I should have realized it sooner but I found myself filtering a collection of items to get all items that matched a certain condition, then doing that again for a different condition. That meant looping over an array twice but I could have just done it once.
Write a generic function for this instead? Lodash has one like this called "partition" for example.
I try and avoid explicit for loops as much as possible as they tend to make code harder to follow and state manipulation is a big source of bugs. Most operations on collections can be decomposed into some easy to follow combination of map, reduce and filter instead (this is a filter variation).
Nice article!
- jacobolus 7y agoThe lodash one might be inspired by the Python itertools "partition" recipe, https://docs.python.org/3/library/itertools.html#itertools-recipes https://docs.python.org/3/library/itertools.html#itertools-r... TFA’s inlined reduce version is much less readable than calling a function which wraps this behavior up.
- seanwilson 7y agoIt's common in functional programming libraries too, usually with the same name. See e.g. OCaml, Haskell and Standard ML.
- np_tedious 7y agoThe "call it builder instead of reduce" comment here was interesting. My knee jerk response was to disagree, being that reduce is well known to mean fold / accumulate. However I've seen a lot of js usages where it does things like modify structures in the containing scope and isn't an FPish fold at all, so a name like that could probably make a lot of sense. Nonetheless for this particular usage, I'd agree that a more specific partition function like lodash's would be an improvement.