Either monad uses code example
Example: either function monad in javascript
class Monad {
pure = () => { throw "pure method needs to be implemented" }
flatMap = (x) => { throw "flatMap method needs to be implemented" }
map = f => this.flatMap(x => new this.pure(f(x)))
}
export class Option extends Monad {
pure = (value) => {
if ((value === null) || (value === undefined)) {
return none;
}
return new Some(value)
}
flatMap = f =>
this.constructor.name === 'None' ?
none :
f(this.value)
equals = (x) => this.toString() === x.toString()
}
class None extends Option {
toString() {
return 'None';
}
}
export const none = new None()
Option.pure = none.pure
export class Some extends Option {
constructor(value) {
super();
this.value = value;
}
toString() {
return `Some(${this.value})`
}
}