UNPKG

type-comparator

Version:

Useful comparator functions written on Typescript

61 lines 2.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const interfaces_1 = require("../interfaces"); const mutations_1 = require("../mutations"); const then_chain_1 = require("./then-chain"); const comparators_1 = require("../comparators"); class Chain { constructor() { this.mutations = []; } reverse() { this.mutations.push({ type: interfaces_1.MutationType.REVERSE }); return this; } map(mapper) { this.mutations.push({ type: interfaces_1.MutationType.MAP, mapper: mapper }); return this; } if(condition) { this.mutations.push({ type: interfaces_1.MutationType.IF, condition }); return new then_chain_1.ThenChain(this); } use(comparatorOrComparators) { if (Array.isArray(comparatorOrComparators)) { return (a, b) => { for (const comparator of comparatorOrComparators) { const result = this.use(comparator)(a, b); if (result !== 0) { return result; } } return 0; }; } return Chain.mutate(comparatorOrComparators, this.mutations); } asc() { return this.use(comparators_1.asc); } desc() { return this.use(comparators_1.desc); } static mutate(fn, descriptors) { let currentFn = fn; for (const descriptor of descriptors.slice().reverse()) { currentFn = ((prevFn) => { switch (descriptor.type) { case interfaces_1.MutationType.REVERSE: return mutations_1.reverse(prevFn); case interfaces_1.MutationType.MAP: return mutations_1.map(descriptor.mapper, prevFn); case interfaces_1.MutationType.IF: return mutations_1.condition(descriptor.condition, descriptor.comparator, prevFn); } })(currentFn); } return currentFn; } } exports.Chain = Chain; //# sourceMappingURL=chain.js.map