logitar-js
Version:
Helper functions distributed by Logitar.
41 lines (40 loc) • 1.52 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.orderByDescending = exports.orderBy = void 0;
function compare(a, b, weight) {
if (typeof a === "undefined" || a === null || typeof b === "undefined" || b === null) {
if ((a !== null && a !== void 0 ? a : null) === null && (b !== null && b !== void 0 ? b : null) !== null) {
return -weight;
}
else if ((a !== null && a !== void 0 ? a : null) !== null && (b !== null && b !== void 0 ? b : null) === null) {
return weight;
}
return 0;
}
return a < b ? -weight : a > b ? weight : 0;
}
/**
* Sorts the specified array.
* @param items The array to sort.
* @param key If provided, the key used to sort an array of objects.
* @param isDescending A value indicating whether or not the sort is reversed (descending).
* @returns A shallow copy of the sorted array.
*/
function orderBy(items, key, isDescending) {
const weight = isDescending ? -1 : 1;
if (key) {
return [...items].sort((a, b) => compare(a[key], b[key], weight));
}
return [...items].sort((a, b) => compare(a, b, weight));
}
exports.orderBy = orderBy;
/**
* Reverse-sorts the specified array.
* @param items The array to sort.
* @param key If provided, the key used to sort an array of objects.
* @returns A shallow copy of the sorted array.
*/
function orderByDescending(items, key) {
return orderBy(items, key, true);
}
exports.orderByDescending = orderByDescending;