radash
radash copied to clipboard
Any interest in `collect`/`collectFirst`?
Two of my favorite utility functions from the Scala programming language are collect and collectFirst. I think these would make a great addition to the library.
-
collect
-- a map+filter combo where, if the result of the mapping function isundefined
, that element is filtered out:
radash.collect([{a: 1}, {b: 2}, {a: 3}], (el) => el.a) // result: [1, 3]
-
collectFirst
-- same as above, but the first defined result is returned immediately:
radash.collectFirst([{a: 1}, {b: 2}, {a: 3}], (el) => el.a) // result: 1
They are essentially more generalized versions of filter
and find
, where you get the opportunity to transform the value(s) at the same time. collect
ends up being a very nice alternative when you don't want to iterate twice but using reduce
just feels like too much.
@rayepps would you be interested in a PR for these additions?