UNPKG

pragmatic-fp-ts

Version:

Opinionated functional programming library with easy use in mind

39 lines (38 loc) 1.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sortWith = void 0; const order = { reversed: 1, equal: 0, ordered: -1, }; const compare = (a, b) => { switch (true) { case a > b: return order.reversed; case a < b: return order.ordered; default: return order.equal; } }; const compareWith = (fns) => { const go = (a, b, idx) => { const f = fns[idx]; const fA = f(a); const fB = f(b); const result = compare(fA, fB); const hasMoreComparisons = idx < fns.length - 1; return result === order.equal && hasMoreComparisons ? go(a, b, idx + 1) : result; }; return (a, b) => go(a, b, 0); }; function sortWith(fns, coll) { if (arguments.length === 1) return (theColl) => sortWith(fns, theColl); else { const sorted = [...(coll !== null && coll !== void 0 ? coll : [])].sort(compareWith(fns)); return sorted; } } exports.sortWith = sortWith;