UNPKG

@jsoldi/hkt

Version:

Higher kinded types for typescript and a few utility monads.

35 lines 1.26 kB
import { functor } from "./functor.js"; import { num } from "../types/primitive.js"; import { chain, pipe } from "../core/utils.js"; const is_fold = Symbol('is_fold'); /** Creates an `IFold` from an `IFoldBase`. */ export function fold(base) { if (is_fold in base) return base; return pipe(base, base => ({ ...functor(base), ...base }), base => { const toArray = (fa) => base.foldl((acc, a) => [...acc, a])([])(fa); const _fold = m => base.foldl(m.append)(m.empty()); const reduce = (acc, f) => base.foldl(f)(acc); const length = fa => base.foldl((acc, _) => acc + 1)(0)(fa); const sum = _fold(num.sum); const all = (p) => (fa) => base.foldl((acc, a) => acc && !!p(a))(true)(fa); const any = (p) => (fa) => base.foldl((acc, a) => acc || !!p(a))(false)(fa); const avg = chain(base.foldl(([sum, count], n) => [sum + n, count + 1])([0, 0]), base.scalar.fmap(([sum, count]) => sum / count)); return { [is_fold]: true, toArray, fold: _fold, reduce, length, sum, avg, any, all, ...base, }; }); } //# sourceMappingURL=fold.js.map