nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions and classes for everyday development needs.
71 lines (70 loc) • 3.07 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.sortAnArray = sortAnArray;
const non_primitives_1 = require("../guards/non-primitives");
const primitives_1 = require("../guards/primitives");
const utils_1 = require("./utils");
/**
* * Sorts an array of strings, numbers, booleans, or objects based on the provided options.
*
* - If the array contains strings, it sorts them alphabetically.
* - If the array contains numbers, it sorts them numerically.
* - If the array contains booleans, it sorts them by their boolean value.
* - If the array contains objects, it sorts them by the specified field in the options `sortByField`.
*
* @param array - The array to sort.
* @param options - Sorting options for objects.
* @returns The sorted array.
*/
function sortAnArray(array, options) {
if (!(0, non_primitives_1.isValidArray)(array))
return array;
// Check if the array contains strings
if ((0, non_primitives_1.isArrayOfType)(array, primitives_1.isString)) {
return [...array].sort((a, b) => options?.sortOrder === 'desc' ?
(0, utils_1.naturalSort)(b, a)
: (0, utils_1.naturalSort)(a, b));
}
// Check if the array contains numbers
if ((0, non_primitives_1.isArrayOfType)(array, primitives_1.isNumber)) {
return [...array].sort((a, b) => options?.sortOrder === 'desc' ? b - a : a - b);
}
// Check if the array contains booleans
if ((0, non_primitives_1.isArrayOfType)(array, primitives_1.isBoolean)) {
return [...array].sort((a, b) => options?.sortOrder === 'desc' ?
Number(b) - Number(a)
: Number(a) - Number(b));
}
// Handle array of objects
if ((0, non_primitives_1.isArrayOfType)(array, non_primitives_1.isObject) && options && 'sortByField' in options) {
return [...array].sort((a, b) => {
const _getKeyValue = (obj, path) => {
return path
.split('.')
.reduce((acc, key) => acc?.[key], obj);
};
const keyA = _getKeyValue(a, options?.sortByField);
const keyB = _getKeyValue(b, options?.sortByField);
if (keyA == null || keyB == null) {
return keyA == null ? 1 : -1;
}
if (typeof keyA === 'string' && typeof keyB === 'string') {
return options?.sortOrder === 'desc' ?
(0, utils_1.naturalSort)(keyB, keyA)
: (0, utils_1.naturalSort)(keyA, keyB);
}
if (typeof keyA === 'number' && typeof keyB === 'number') {
return options?.sortOrder === 'desc' ?
keyB - keyA
: keyA - keyB;
}
if (typeof keyA === 'boolean' && typeof keyB === 'boolean') {
return options?.sortOrder === 'desc' ?
Number(keyB) - Number(keyA)
: Number(keyA) - Number(keyB);
}
return 0;
});
}
return array;
}