fp-ts-std
Version:
The missing pseudo-standard library for fp-ts.
45 lines (44 loc) • 2.07 kB
JavaScript
import * as E from "fp-ts/Either";
import * as O from "fp-ts/Option";
import { constant, flow, pipe } from "fp-ts/function";
import { mapBoth as _mapBoth } from "./Bifunctor";
import { curry2 } from "./Function";
import * as L from "./Lazy";
import { add } from "./Number";
import { GT, LT } from "./Ordering";
export const unsafeUnwrap = (x) => {
if (E.isLeft(x))
throw Error("Unwrapped `Left`", { cause: x.left });
return x.right;
};
export const unsafeUnwrapLeft = (x) => {
if (E.isRight(x))
throw Error("Unwrapped `Right`", { cause: x.right });
return x.left;
};
export const unsafeExpect = (S) => flow(E.mapLeft(S.show), unsafeUnwrap);
export const unsafeExpectLeft = (S) => flow(E.map(S.show), unsafeUnwrapLeft);
export const mapBoth = _mapBoth(E.Bifunctor);
export const match2 = (onLeftLeft, onLeftRight, onRightLeft, onRightRight) => (mab) => (mcd) => pipe(mab, E.match(a => pipe(mcd, E.match(c => onLeftLeft(a)(c), d => onLeftRight(a)(d))), b => pipe(mcd, E.match(c => onRightLeft(b)(c), d => onRightRight(b)(d)))));
export const getOrd = (EO) => (AO) => ({
...E.getEq(EO, AO),
compare: (x, y) => match2(curry2(EO.compare), constant(constant(LT)), constant(constant(GT)), curry2(AO.compare))(x)(y),
});
export const getBounded = (BE) => (BA) => ({
...getOrd(BE)(BA),
top: E.right(BA.top),
bottom: E.left(BE.bottom),
});
export const getEnum = (EE) => (EA) => ({
...getBounded(EE)(EA),
succ: E.match(flow(EE.succ, O.matchW(L.lazy(() => E.right(EA.bottom)), E.left), O.some), flow(EA.succ, O.map(E.right))),
pred: E.match(flow(EE.pred, O.map(E.left)), flow(EA.pred, O.matchW(L.lazy(() => E.left(EE.top)), E.right), O.some)),
toEnum: n => {
const ec = L.execute(EE.cardinality);
return n < ec
? pipe(n, EE.toEnum, O.map(E.left))
: pipe(n - ec, EA.toEnum, O.map(E.right));
},
fromEnum: E.match(EE.fromEnum, flow(EA.fromEnum, n => n + L.execute(EE.cardinality))),
cardinality: pipe(L.of(add), L.ap(EE.cardinality), L.ap(EA.cardinality)),
});