/** * * Maybe Monad * @Source: https://codewithstyle.info/advanced-functional-programming-in-typescript-maybe-monad/ * @Modified by: @lucascalion - 28/08/2019 * **/ export class Maybe { private constructor(private value: T | null) {} static some (value: T): Maybe { if (!value) { throw Error("Provided value must not be empty"); } return new Maybe(value); } static none (): Maybe { return new Maybe(null); } static fromValue (value: T): Maybe { return value ? Maybe.some(value) : Maybe.none(); } getOrElse(defaultValue: T): T { return this.value === null ? defaultValue : this.value; } map(f: (wrapped: T) => R): Maybe { if (this.value === null) { return Maybe.none(); } else { return Maybe.fromValue(f(this.value)); } } }