UNPKG

sorting-query

Version:

An utility to parse and define types of sorting queries

114 lines (113 loc) 2.82 kB
// src/SORT_PREFIX.ts var SORT_PREFIX = "orderBy."; // src/utils.ts function opposite(comparator) { return (a, b) => -comparator(a, b); } function combineComparators(...comparators) { return (a, b) => { for (const comparator of comparators) { const result = comparator(a, b); if (result !== 0) return result; } return 0; }; } function indifferentComparator(a, b) { return 0; } function getSorted(ascendingComparators, orderBy, items) { const comparators = orderBy.map((orderBy2) => { const { key, order } = orderBy2; const ascendingComparator = ascendingComparators[key]; if (!ascendingComparator) return indifferentComparator; const propertyComparator = order === "asc" ? ascendingComparator : opposite(ascendingComparator); return (a, b) => propertyComparator(a[key], b[key]); }); const combinedComparator = combineComparators(...comparators); const res = [...items]; res.sort(combinedComparator); return res; } function numberAscending(a, b) { return a - b; } function stringAscending(a, b) { if (a == null && b == null) return 0; if (a == null) return 1; if (b == null) return -1; return a.localeCompare(b); } function timestampNewerFirst(a, b) { return b - a; } function isValidOrder(value) { return value === "asc" || value === "desc"; } function isSortQueryParam(value) { if (typeof value !== "string") return false; return value.startsWith(SORT_PREFIX); } function getSortedProperty(value) { return value.slice(SORT_PREFIX.length); } function parseSortingParams(params) { const res = []; const keys = Object.keys(params); for (const param of keys) { if (!isSortQueryParam(param)) continue; const order = params[param]; if (!isValidOrder(order)) continue; const sortedProperty = getSortedProperty(param); res.push({ key: sortedProperty, order }); } return res; } function isValidSortedColumns(sortableKeys, value) { if (!Array.isArray(value)) return false; const sortedColumns = value; const s = new Set(sortableKeys); for (const column of sortedColumns) { if (!column) return false; if (!s.has(column.key)) return false; if (column.order !== "desc" && column.order !== "asc") return false; } return true; } function toQueryParams(sortedColumns) { const res = /* @__PURE__ */ Object.create(null); for (const { key, order } of sortedColumns) { res[`orderBy.${key.toString()}`] = order; } return res; } export { SORT_PREFIX, getSorted, getSortedProperty, indifferentComparator, isSortQueryParam, isValidOrder, isValidSortedColumns, numberAscending, parseSortingParams, stringAscending, timestampNewerFirst, toQueryParams }; //# sourceMappingURL=index.mjs.map