radash icon indicating copy to clipboard operation
radash copied to clipboard

Any interest in `collect`/`collectFirst`?

Open adamhamlin opened this issue 1 year ago • 3 comments

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 is undefined, 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?

adamhamlin avatar Mar 02 '23 05:03 adamhamlin