UNPKG

morphir-elm

Version:
80 lines (79 loc) 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Maybe = exports.Nothing = exports.Just = void 0; const basics_1 = require("./basics"); function MaybeOps(maybe) { return { withDefault(defaultValue) { if (maybe.kind === 'Just') { return maybe.value; } return defaultValue; }, map(fn) { if (maybe.kind === 'Just') { return Just(fn(maybe.value)); } return Nothing(); }, andThen(fn) { if (maybe.kind === 'Just') { return fn(maybe.value); } return Nothing(); }, equal(other) { if (maybe.kind === 'Just' && other.kind === 'Just') { return (0, basics_1.equal)(maybe.value, other.value); } return maybe.kind === other.kind; } }; } /** * Create a Just value, which represents a value that exists. * @param value the value to wrap in a Just. * @return a new Just value. * @example * ```ts * const maybeValue = Maybe.Just(42); // maybeValue is Just(42) * ``` */ function Just(value) { const v = { kind: 'Just', value }; return Object.assign(v, MaybeOps(v)); } exports.Just = Just; /** * Create a Nothing value, which represents a value that does not exist. * @return a new Nothing value. * @example * ```ts * const maybeValue = Maybe.Nothing<number>(); // maybeValue is Nothing * ``` */ function Nothing() { const v = { kind: 'Nothing' }; return Object.assign(v, MaybeOps(v)); } exports.Nothing = Nothing; /** * Create a Maybe value from a value that may be null or undefined. * If the value is null or undefined, a Nothing value is returned. * Otherwise, a Just value is returned. * @param value the value to wrap in a Maybe. * @return a new Maybe value. * @example * ```ts * const maybeValue = Maybe.Maybe(42); // maybeValue is Just(42) * ... * const maybeValue = Maybe.Maybe(null); // maybeValue is Nothing * ``` */ function Maybe(value) { if (value === null || value === undefined) { return Nothing(); } return Just(value); } exports.Maybe = Maybe;