Do you consider implementing `Maybe#orElse()` method?
lancedikson opened this issue · 6 comments
Hi, thanks for the lib. Love it!
Do you find Maybe#orElse()
method useful and consider implementing it? I find it useful in order to gracefully avoid such constructions:
let maybeGTINs = getGTINsFromString(string);
if (maybeGTINs.isNone()) {
let maybeGTINs = just(['default']);
}
with something like this:
const maybeGTINs = getGTINsFromString(string).orElse(['default']);
Monet's seem to have one, but it accepts a Maybe instance for some reason. I guess, the best implementation would be the one mentioned in this article: https://jrsinclair.com/articles/2016/marvellously-mysterious-javascript-maybe-monad/
Maybe.prototype.orElse = function(default) {
if (this.isNothing()) {
return Maybe.of(default);
}
return this;
};
Hi, thank you a lot for the words
Sounds great!
Will implement it soon.
Great! I have some spare time, so if you would like me to propose a PR, just let me know ;)
But I'm thinking about the name and semantic, because, as an example, It's presented natively in Haskell via Alternative
type class. The same example in Haskell looks like:
bannerSrc = getUserBanner user <|> Just "/assets/banners/default-banner.jpg"
This mechanism is more controllable because I can make longer orElse
chains like this:
bannerSrc = getUserBanner user <|>
getAnotherBanner <|>
getMockBannerFor user <|>
Just "/assets/banners/default-banner.jpg"
I'm thinking about Alternative
interface implementation for Either
and Maybe
with or
method like this:
interface Alternative<T> {
or: (x: Alternative<T>) => Alternative<T>
}
And the example will be like:
const bannerSrc = getUserBanner(user).or(just( "/assets/banners/default-banner.jpg"));
// or
const bannerSrc = getUserBanner(user)
.or(getAnotherBanner())
.or(getMockBannerFor(user))
.or(just( "/assets/banners/default-banner.jpg"));
What do you think?
Yeah, looks great to me!
Done in ^2.1.2
version
Wow, that was fast! Thank you!