Skip to content

Instantly share code, notes, and snippets.

@venil7
Created May 11, 2018 11:35
Show Gist options
  • Save venil7/a37f04f7bc613323fb73c77a0865b992 to your computer and use it in GitHub Desktop.
Save venil7/a37f04f7bc613323fb73c77a0865b992 to your computer and use it in GitHub Desktop.
Maybe monad in TypeScript
class Maybe<T> {
constructor(private val: T) { }
with<Z>(f: (z: T) => Z): Maybe<Z> {
return new Maybe(this.return(f));
}
return<Z>(f: (z: T) => Z): Z {
try {
return (f(this.val));
} catch (err) {
return undefined;
}
}
}
const obj = { a: { b: { c: 123 } } };
const v = new Maybe(obj)
.with(x => x.a.z)
.with(x => x.b.h)
.return(x => x.c.g);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment