@MichalZalecki
/ˈməʊnad/ or /ˈmɒnad/
In functional programming, monads are a way to build computer programs by joining simple components in robust ways.
‒ wikipedia.org
Specification for interoperability of common algebraic structures in JavaScript
1 commit, 1 character change
class Identity { static of(value) { return new Identity(value); } constructor(public value) {} chain(fn) { return fn(this.value); }
ap(m) { return m.map(x => x(this.value)); }
map(fn) { return Identity.of(fn(this.value)); } }
class Left { constructor(public value) {} map(_fn) { return this; } } class Right { map(fn) { try { return Right.of(fn(this.value)); } catch (err) { return Left.of(err); } } } type Either = Left | Right;
class Nothing { map(_fn) { return this; } } class Just { map(fn) { try { return Just.of(fn(this.value)); } catch (err) { return new Nothing(); } } } type Maybe = Nothing | Just;
class IO { static of(value, ...args) { return new IO(value, ...args); } map(fn) { return IO.of(fn(this.value)); } run() { this.value(...this.args); } equals(m) { return deepEqual(this, m); } }
function* lazyMap(iterable, fn) { for (let elem of iterable) { yield fn(elem); } }
export class List { map(fn) { return List.of(lazyMap(this.value, fn)); } *[Symbol.iterator]() { yield* this.value; } }
Promise.resolve(URL) .then(axios.get) .then(appendPosts) .catch((err) => { ... });
Continuation.of(URL) .chain(axios.get) .chain(appendPosts) .chain(m => if (m instanceof Error) {})
@MichalZalecki