UNPKG

fp-ts-std

Version:

The missing pseudo-standard library for fp-ts.

40 lines (39 loc) 1.79 kB
import * as O from "fp-ts/Option"; import * as B from "fp-ts/boolean"; import { constant, flow, pipe } from "fp-ts/function"; import { altAllBy as _altAllBy, pureIf as _pureIf } from "./Alternative"; import { invert as invertBool } from "./Boolean"; import * as L from "./Lazy"; import { toMonoid as _toMonoid } from "./Monoid"; import { decrement, increment } from "./Number"; export const unsafeExpect = (msg) => (x) => { if (O.isNone(x)) throw Error("Unwrapped `None`", { cause: new Error(msg) }); return x.value; }; export const unsafeUnwrap = (x) => { if (O.isNone(x)) throw Error("Unwrapped `None`"); return x.value; }; export const noneAs = () => O.none; export const invert = (eq) => (val) => flow(O.exists(x => eq.equals(x, val)), B.match(() => O.some(val), constant(O.none))); export const toMonoid = _toMonoid(O.Foldable); export const memptyWhen = (x) => (m) => x ? O.none : m(); export const memptyUnless = flow(invertBool, memptyWhen); export const pureIf = _pureIf(O.Alternative); export const altAllBy = _altAllBy(O.Alternative); export const getBounded = (B) => ({ ...O.getOrd(B), top: O.some(B.top), bottom: O.none, }); export const getEnum = (E) => ({ ...getBounded(E), succ: O.match(L.lazy(() => O.some(O.some(E.bottom))), flow(E.succ, O.map(O.some))), pred: O.map(E.pred), toEnum: n => n === 0 ? O.some(O.none) : pipe(n, decrement, E.toEnum, O.map(O.some)), fromEnum: O.match(constant(0), flow(E.fromEnum, increment)), cardinality: pipe(E.cardinality, L.map(increment)), }); export const match2 = (onNone, onSomeFst, onSomeSnd, onSomeBoth) => (mx) => (my) => pipe(mx, O.match(L.lazy(() => pipe(my, O.match(onNone, onSomeSnd))), x => pipe(my, O.match(L.lazy(() => onSomeFst(x)), y => onSomeBoth(x)(y)))));