import { DeserializationError, InvalidStateError, UnwrapCustomError } from "./errors"; import { bind, combine, identity, isWrappedFunction, noop } from "./runtime"; import type { MaybePromiseLike, Nullable, AnyParameters, Mapper, Pair, Alternative, Monad, Container, Pipe, AsyncTap, Zip } from "./types"; export const enum MaybeState { None = "None", Just = "Just" } const name = "Maybe"; export function none(): Maybe { return None.create(); } export function just(value: T): Maybe { return Just.create(value); } export { just as from }; function cast(constructor: MaybeConstructor): Maybe { if (isMaybe(constructor)) { return constructor; } /* istanbul ignore next */ throw new InvalidStateError(); } class MaybeConstructor implements Monad, Alternative, Container, Pipe, AsyncTap, Zip { //#region Functor map( map: Mapper, ...parameters: P ): Maybe { return this.chain(combine(bind(map, parameters), just)); } mapJust( map: Mapper, ...parameters: P ): Maybe { return this.chain(combine(bind(map, parameters), just)); } mapNullable( map: Mapper, ...parameters: P ): Maybe { return this.chain(combine(bind(map, parameters), fromNullable)); } async asyncMap( map: Mapper, P>, ...parameters: P ): Promise> { return await this.map(map, ...parameters).await(); } //#endregion //#region Applicative pure(value: Va): Maybe { return just(value); } apply( this: Maybe>, argument: Maybe, ...parameters: P ): Maybe; apply( this: Maybe, argument: Maybe>, ...parameters: P ): Maybe; apply( this: Maybe>, argument: Maybe>, ...parameters: P ): Maybe { return this.zip(argument).map(([current, argument]): B => { if (isWrappedFunction(current)) { return current(argument as A, ...parameters); } if (isWrappedFunction(argument)) { return argument(current as A, ...parameters); } throw new InvalidStateError( InvalidStateError.Messages.APPLY_SHOULD_BE_FUNCTION ); }); } asyncApply( this: Maybe, P>>, argument: Maybe, ...parameters: P ): Promise>; asyncApply( this: Maybe, map: Maybe, P>>, ...parameters: P ): Promise>; async asyncApply( this: Maybe, P>>, argument: Maybe, P>>, ...parameters: P ): Promise> { return await this.zip(argument) .map(([current, argument]): B => { if (isWrappedFunction(current)) { return current(argument as A, ...parameters); } if (isWrappedFunction(argument)) { return argument(current as A, ...parameters); } throw new InvalidStateError( InvalidStateError.Messages.APPLY_SHOULD_BE_FUNCTION ); }) .await(); } //#endregion //#region Monad chain( map: Mapper, P>, ...parameters: P ): Maybe { return this.fold>(none, bind(map, parameters)); } async asyncChain( map: Mapper>, P>, ...parameters: P ): Promise> { const result = await this.map(map, ...parameters).await(); return result.join(); } async await(this: Maybe>): Promise> { return await this.fold>>(none, async (value) => just(await value) ); } join(this: Maybe>): Maybe { return this.chain(identity); } //#endregion //#region Alternative default(value: Va): Maybe { return this.or(just(value)); } or(x: Maybe): Maybe { return this.orLazy(() => x); } orLazy(factory: () => Maybe): Maybe { return this.fold(factory, () => cast(this)); } async orAsync( factory: () => MaybePromiseLike> ): Promise> { return await this.fold(factory, () => cast(this)); } //#endregion //#region Tap tap

( callback: Mapper, ...parameters: P ): Maybe { this.map(callback, ...parameters); return cast(this); } async asyncTap

( callback: Mapper, P>, ...parameters: P ): Promise> { await this.asyncMap(callback, ...parameters); return cast(this); } //#endregion // Pipe pipe( pipe: Mapper, V, P>, ...parameters: P ): V { return bind(pipe, parameters)(cast(this)); } //#region Matching isJust(predicate: (value: Va) => value is T): this is Just; isJust(predicate?: (value: Va) => boolean): this is Just; isJust(predicate?: (value: Va) => boolean): this is Just { return isJust(this) && (!predicate || predicate(this.value)); } isNone(): this is None { return isNone(this); } fold(mapNone: Mapper, mapJust: Mapper): A | B { if (this.isJust()) { return mapJust(this.value); } if (this.isNone()) { return mapNone(); } /* istanbul ignore next */ throw new InvalidStateError(); } match(matcher: { readonly just: (value: Va) => A; readonly none: () => B; }): A | B { return this.fold(matcher.none, matcher.just); } //#endregion //#region Container unwrap(message: string = UnwrapCustomError.Messages.MAYBE_IS_NONE): Va { return this.fold(() => UnwrapCustomError.inlineThrow(message), identity); } unwrapOr(value: T): Va | T { return this.unwrapOrElse(() => value); } unwrapOrElse(value: () => T): Va | T { return this.fold(value, identity); } //#endregion // Zip zip(maybe: Maybe): Maybe> { return this.chain((value) => maybe.map((right) => [value, right])); } // Maybe specific filter(filter: (input: Va) => input is T): Maybe; filter(filter: (input: Va) => boolean): Maybe; filter(filter: (input: Va) => boolean): Maybe { return this.chain((value) => (filter(value) ? just(value) : none())); } flatMap( map: Mapper, ...parameters: P ): T | undefined { return this.fold(noop, bind(map, parameters)); } } Object.freeze(MaybeConstructor); Object.freeze(MaybeConstructor.prototype); type SerializedJust = Readonly<{ name: typeof name; type: MaybeState.Just; value: T; }>; class Just extends MaybeConstructor implements SerializedJust { static create(value: T): Just { return new Just(value); } get [Symbol.toStringTag](): MaybeState.Just { return MaybeState.Just; } get name(): typeof name { return name; } get type(): MaybeState.Just { return MaybeState.Just; } /** * @deprecated Use {@link getValue} instead; * * @type {T} * @memberof Just */ public readonly value: T; private constructor(value: T) { super(); this.value = value; Object.freeze(this); } getValue(): T { return this.value; } toJSON(): SerializedJust { return { name: this.name, type: this.type, value: this.value }; } } Object.freeze(Just); Object.freeze(Just.prototype); type SerializedNone = { name: typeof name; type: MaybeState.None }; class None extends MaybeConstructor implements SerializedNone { static readonly instance = new None(); static create(): None { return None.instance; } get value(): undefined { return undefined; } getValue(): undefined { return; } get [Symbol.toStringTag](): MaybeState.None { return MaybeState.None; } get name(): typeof name { return name; } get type(): MaybeState.None { return MaybeState.None; } private constructor() { super(); Object.freeze(this); } toJSON(): SerializedNone { return { name: this.name, type: this.type }; } } Object.freeze(None); Object.freeze(None.prototype); export type Maybe = Just | None; export type SerializedMaybe = SerializedJust | SerializedNone; export const isJust = (value: unknown | Maybe): value is Just => value instanceof Just; export const isNone = (value: unknown | Maybe): value is None => // Better: value === None.instance value instanceof None; export const isMaybe = (value: unknown | Maybe): value is Maybe => isJust(value) || isNone(value); export function chain( map: (v: A, ...parameters: P) => MaybePromiseLike>, ...parameters: P ): (maybe: Maybe) => Promise> { return (maybe) => maybe.asyncChain(bind(map, parameters)); } /** * @template T * @param {SerializedMaybe} serialized * @throws {DeserializationError} - {@link DeserializationError} * @return {Maybe} */ export function fromJSON(serialized: SerializedMaybe): Maybe { if (serialized.name !== name) { throw new DeserializationError( DeserializationError.Messages.EXPECTED_MAYBE ); } if (serialized.type === MaybeState.Just) { return just(serialized.value); } return none(); } export function merge(values: [Maybe]): Maybe<[V1]>; export function merge(values: [Maybe, Maybe]): Maybe<[V1, V2]>; export function merge( values: [Maybe, Maybe, Maybe] ): Maybe<[V1, V2, V3]>; export function merge( values: [Maybe, Maybe, Maybe, Maybe] ): Maybe<[V1, V2, V3, V4]>; export function merge( values: [Maybe, Maybe, Maybe, Maybe, Maybe] ): Maybe<[V1, V2, V3, V4, V5]>; export function merge( values: [Maybe, Maybe, Maybe, Maybe, Maybe, Maybe] ): Maybe<[V1, V2, V3, V4, V5, V6]>; export function merge(values: Maybe[]): Maybe; export function merge(values: Maybe[]): Maybe { if (values.some((maybe) => maybe.isNone())) { return none(); } return just([...filterMap(values, identity)]); } export function fromNullable(value: Nullable): Maybe { return value !== null && value !== undefined ? just(value) : none(); } export function* iterator( callback: () => Maybe ): Generator { let result: Maybe; while ((result = callback()).isJust()) { yield result.getValue(); } } export async function* asyncIterator( callback: () => MaybePromiseLike>> ): AsyncGenerator { let result: Maybe>; while ((result = await callback()).isJust()) { yield await result.getValue(); } } export function* filterMap( iterable: Iterable, filterMap: (value: A, index: number) => Maybe ): Generator { let index = 0; for (const value of iterable) { const processed = filterMap(value, index++); if (processed.isJust()) { yield processed.unwrap(); } } }