Skip to content

Instantly share code, notes, and snippets.

@venil7
Last active May 24, 2020 10:22
Show Gist options
  • Save venil7/fd80fbccb33429d3e322cdb8f43a5a77 to your computer and use it in GitHub Desktop.
Save venil7/fd80fbccb33429d3e322cdb8f43a5a77 to your computer and use it in GitHub Desktop.
TypeScript Maybe<T> monad
type Maybe<T> = {
map: <T2>(func: (t: T) => T2) => Maybe<T2>,
then: <T2>(func: (t: T) => Maybe<T2>) => Maybe<T2>,
value: (fallback: T) => T
};
const maybe = function <T>(a: T | undefined | null): Maybe<T> {
const value: [T] | [] = (a !== null && a !== void 0) ? [a] : [];
return {
map: function <T2>(func: (t: T) => T2): Maybe<T2> {
return value.length
? maybe(func(value[0]))
: maybe<T2>(null)
},
then: function <T2>(func: (t: T) => Maybe<T2>): Maybe<T2> {
return value.length
? func(value[0])
: maybe<T2>(null)
},
value: function (fallback: T): T {
return value.length ? value[0] : fallback;
}
};
};
const v = 5;
const m = maybe<number>(v);
console.log(m.map(x => x * 2).map(x => `--> ${x} <<--`).value('no value'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment