UNPKG

maybe-monade

Version:

Maybe monad implementation in Typescript

76 lines (75 loc) 2.85 kB
import { f, MaybeCallback } from "./MaybeCallback"; /** * A wrapper (abstraction) for a value that may or may not exist */ export declare class Maybe<T> { private value; /** * Return an instance of Maybe wrapping an empty value */ static none<T>(): Maybe<T>; /** * if the provided value is not null or undefined, return an instance of Maybe wrapping a nonempty value, * otherwise throw an error * @param value the value to wrap in an instance of Maybe */ static some<T>(value: T): Maybe<T>; /** * return an instance of Maybe wrapping the provided value, otherwise return an instance of empty Maybe * @param value value to wrap into a Maybe */ static fromValue<T>(value: T): Maybe<T>; /** * return an instance of Maybe wrapping the provided callback, otherwise return an instance of empty Maybe * @param func callback to wrap into a Maybe */ static fromFunction<R>(func: f<R>): MaybeCallback<R>; private constructor(); /** * return true if the wrapped value is empty, false otherwise */ isEmpty(): boolean; /** * return true if the wrapped value is nonempty, false otherwise */ exists(): boolean; /** * get the wrapped value if nonempty, otherwise throw an error */ get(): T; /** * return the wrapped value if nonempty, otherwise the provided default value. */ getOrElse(defaultValue: T): T; /** * return the value if nonempty, otherwise invoke alternative * and return the result of that invocation. * @param alternative the function to invoke */ orElse(alternative: () => Maybe<T>): Maybe<T>; /** * if the value exists, apply the provided mapping function to it, * return an instance of Maybe wrapping the result. * @param fmap the function to apply */ map<R>(fmap: (value: T) => R): Maybe<R>; /** * if the wrapped value is nonempty, apply the provided mapping function to it, * return that result, otherwise return an instance of empty Maybe. * @param func the function to apply */ flatMap<R>(func: (value: T) => Maybe<R>): Maybe<R>; /** * apply func to the wrapped value then return an instance of Maybe wrapping * the value before applying the func function. * func could be console.log for example. * @param func function to apply */ do(func: (value: T) => void): Maybe<T>; /** * if the wrapped value is nonempty, and the value matches the given predicate, * return a Maybe wrapping the value, otherwise return an instance of empty Maybe * @param predicate a predicate to apply to the value if nonempty */ filter(predicate: (x: T) => boolean): Maybe<T>; }