UNPKG

@mvst/ts-unions

Version:

TypeScript union types for Maybe and RemoteData with pattern matching

33 lines (32 loc) 1.04 kB
import { curry } from "./utils.js"; function nothing() { return { type: "Nothing" }; } function just(value) { return { type: "Just", value }; } function isJust(maybe) { return maybe.type === "Just"; } function isNothing(maybe) { return maybe.type === "Nothing"; } const withDefault = curry(function withDefault(defaultValue, maybe) { return isJust(maybe) ? maybe.value : defaultValue; }); const when = curry(function when(pattern, maybe) { const { nothing, just, _ = Function.prototype } = pattern; switch (maybe.type) { case "Nothing": return typeof nothing === "function" ? nothing() : _(); case "Just": return typeof just === "function" ? just(maybe.value) : _(); } }); const map = curry(function map(fn, maybe) { return isJust(maybe) ? just(fn(maybe.value)) : maybe; }); const andThen = curry(function andThen(fn, maybe) { return isJust(maybe) ? fn(maybe.value) : maybe; }); export { andThen, isJust, isNothing, just, map, nothing, when, withDefault };