emmanueltouzery / prelude-ts

Functional programming, immutable collections and FP constructs for typescript and javascript
ISC License
377 stars 21 forks source link

Add `Option.orCall(f)` function #39

Closed gabebw closed 4 years ago

gabebw commented 4 years ago

This is like getOrCall, but does not unwrap a Some .

It behaves like this:

Option.some(1).orCall(() => Option.some(9)) // Option.some(1)
Option.none().orCall(() => Option.some(1))  // Option.some(1)

Among other places, this method is useful when calling a recursive function that returns Option<T>. Instead of doing something like this:

function recurse(): Option<T> {
  const option = Option.of(something);
  if(option.isSome()){
    return option;
  } else {
    return recurse(somethingElse);
  }
}

...it can now be written like this, matching ts-prelude's fluent style:

function recurse(): Option<T> {
  const option = Option.of(something);
  return option.maybe(() => {
    recurse(somethingElse);
  });
}
emmanueltouzery commented 4 years ago

Yes, a lazy orElse. We have getOrElse/getOrCall, so orElse/or call makes sense, thanks for this 👍

gabebw commented 4 years ago

Thanks for a great and useful library!