monet / monet.js

monet.js - Monadic types library for JavaScript
https://monet.github.io/monet.js/
MIT License
1.6k stars 114 forks source link

Shortcut for flatMap on possibly falsy data (flatMapFromFalsy) #217

Open tvedtorama opened 5 years ago

tvedtorama commented 5 years ago

I find myself writing this all the time:

maybe.flatMap(x => Maybe.fromFalsy(x.value)).

It would be very useful to have an

maybe.flatMapFromFalsy(x => x.value)

or

maybe.flatMap(x => x.value, Maybe.fromFalsy)
// Which can also be used with other constructors:
maybe.flatMap(x => x.value, Maybe.fromNull)

Does this make sense, or am I perhaps using the library a bit wrong?

ulfryk commented 5 years ago

@tvedtorama - your request is for sure a thing. I also find myself composing flat map with fromNull

Without need to access nested properties solution would be using the constructor as a passed lambda:

maybe.flatMap(Maybe.fromFalsy)

but for mentioned above case there are no tools in monet. You can always use compose from any other functional library:

maybe.flatMap(compose(Maybe.fromFalsy, x => x.value))

But as this seems to be quite a common use case, I'd think about how it can be enhanced in a nicest way :)