UNPKG

ts-prime

Version:

A utility library for JavaScript and Typescript.

90 lines (89 loc) 3.37 kB
import { clone } from './clone'; import { isArray, isObject } from './guards'; import { pipe } from './pipe'; import { purry } from './purry'; import { type } from './type'; export function sortBy() { return purry(_sortBy, arguments); } function _sortBy(array, fn) { var copied = clone(array); var sortedArray = copied.sort(function (a, b) { var aa = fn(a); var bb = fn(b); /** Default comparison function */ var defaultCompare = function (a, b) { return a < b ? -1 : a > b ? 1 : 0; }; /** Easy way to swap order */ var order = function (order, sortFn) { switch (order) { case 'asc': return function (a, b) { return sortFn(a, b); }; case 'desc': return function (a, b) { return sortFn(b, a); }; } }; var sortComplex = function (aC, bC) { if (type(aC) !== type(bC)) { throw new Error("Can't compare two different types"); } if (isObject(aC) && isObject(bC)) { var sortFn = order(aC.order || 'asc', bC.compare || defaultCompare); var orderScore = sortFn(aC.value, bC.value); return orderScore; } if (isObject(aC)) { throw new Error('Impossible error'); // Code should never throw this error .Using this only as typescript guard } if (isObject(bC)) { throw new Error('Impossible error'); // Code should never throw this error. Using this only as typescript guard } return order('asc', defaultCompare)(aC, bC); }; if (isArray(aa) && isArray(bb)) { if (aa.length !== bb.length) { throw new Error('Critical sortBy error. Comparison properties should be static'); } for (var _i = 0, _a = new Array(aa.length).fill(0).map(function (_, i) { return i; }); _i < _a.length; _i++) { var sIndex = _a[_i]; var aaV = aa[sIndex]; var bbV = bb[sIndex]; if (type(aaV) !== type(bbV)) { throw new Error("Can't compare two different types"); } var result = sortComplex(aaV, bbV); if (result !== 0) { return result; } } } if (type(aa) !== type(bb)) { throw new Error("Can't compare two different types"); } if (isObject(aa) && isObject(bb)) { var sortFn = order(aa.order || 'asc', aa.compare || defaultCompare); var orderScore = sortFn(aa.value, bb.value); return orderScore; } if (isObject(aa)) { throw new Error('Impossible error'); // Code should never throw this error .Using this only as typescript guard } if (isObject(bb)) { throw new Error('Impossible error'); // Code should never throw this error. Using this only as typescript guard } return sortComplex(aa, bb); }); return sortedArray; } var l = [ { a: 4, x: 74, }, ]; pipe(l, sortBy(function (a) { return a.a; }));