ts-prime
Version:
A utility library for JavaScript and Typescript.
93 lines (92 loc) • 3.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var clone_1 = require("./clone");
var guards_1 = require("./guards");
var pipe_1 = require("./pipe");
var purry_1 = require("./purry");
var type_1 = require("./type");
function sortBy() {
return purry_1.purry(_sortBy, arguments);
}
exports.sortBy = sortBy;
function _sortBy(array, fn) {
var copied = clone_1.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_1.type(aC) !== type_1.type(bC)) {
throw new Error("Can't compare two different types");
}
if (guards_1.isObject(aC) && guards_1.isObject(bC)) {
var sortFn = order(aC.order || 'asc', bC.compare || defaultCompare);
var orderScore = sortFn(aC.value, bC.value);
return orderScore;
}
if (guards_1.isObject(aC)) {
throw new Error('Impossible error'); // Code should never throw this error .Using this only as typescript guard
}
if (guards_1.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 (guards_1.isArray(aa) && guards_1.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_1.type(aaV) !== type_1.type(bbV)) {
throw new Error("Can't compare two different types");
}
var result = sortComplex(aaV, bbV);
if (result !== 0) {
return result;
}
}
}
if (type_1.type(aa) !== type_1.type(bb)) {
throw new Error("Can't compare two different types");
}
if (guards_1.isObject(aa) && guards_1.isObject(bb)) {
var sortFn = order(aa.order || 'asc', aa.compare || defaultCompare);
var orderScore = sortFn(aa.value, bb.value);
return orderScore;
}
if (guards_1.isObject(aa)) {
throw new Error('Impossible error'); // Code should never throw this error .Using this only as typescript guard
}
if (guards_1.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_1.pipe(l, sortBy(function (a) { return a.a; }));