Skip to content

Instantly share code, notes, and snippets.

@toburger
Created October 30, 2015 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toburger/93f4a412ff7f01282b41 to your computer and use it in GitHub Desktop.
Save toburger/93f4a412ff7f01282b41 to your computer and use it in GitHub Desktop.
function maybe(value) {
const isEmpty = () => value === undefined || value === null;
const nonEmpty = () => !isEmpty();
return {
map(f) { return isEmpty() ? this : maybe(f(value)) },
getOrElse(n) { return isEmpty() ? n : value },
isEmpty: isEmpty,
nonEmpty: nonEmpty
}
}
@toburger
Copy link
Author

usage:

let p = { firstName: "foo" };
//let p = null;

// does throw a runtime error if p or firstName is null
//document.write(p.firstName.toUpperCase())

let chain = maybe(p)
  .map(p => p.firstName)
  .map(fn => fn.toUpperCase())
  .getOrElse("bar");

document.write(chain);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment