UNPKG

@primer/react

Version:

An implementation of GitHub's Primer Design System using React

88 lines (87 loc) 2.53 kB
//#region src/DataTable/sorting.ts const SortDirection = { ASC: "ASC", DESC: "DESC", NONE: "NONE" }; const DEFAULT_SORT_DIRECTION = SortDirection.ASC; function transition(direction) { if (direction === SortDirection.ASC) return SortDirection.DESC; return SortDirection.ASC; } /** * A sort strategy for comparing any two values */ function basic(a, b) { return a === b ? 0 : a < b ? -1 : 1; } /** * A sort strategy for comparing two `Date` values. Also includes support for * values from `Date.now()` */ function datetime(a, b) { const timeA = a instanceof Date ? a.getTime() : a; const timeB = b instanceof Date ? b.getTime() : b; return timeA > timeB ? 1 : timeA < timeB ? -1 : 0; } /** * Compare two numbers using alphanumeric, or natural order, sorting. This * sorting function breaks up the inputs into groups of text and numbers and * compares the different sub-groups of each to determine the order of a set of * strings * * @see https://en.wikipedia.org/wiki/Natural_sort_order */ function alphanumeric(inputA, inputB) { const groupsA = getAlphaNumericGroups(inputA); const groupsB = getAlphaNumericGroups(inputB); while (groupsA.length !== 0 && groupsB.length !== 0) { const a = groupsA.shift(); const b = groupsB.shift(); if (a === b) continue; else if (typeof a === "string" && typeof b === "string") return a.localeCompare(b); else if (typeof a === "number" && typeof b === "number") return a > b ? 1 : -1; else if (typeof a === "number" && typeof b === "string") return -1; else if (typeof a === "string" && typeof b === "number") return 1; else if (a === void 0 || b === void 0) break; } return groupsA.length > groupsB.length ? 1 : -1; } /** * Break up the given input string into groups of text and numbers */ function getAlphaNumericGroups(input) { const groups = []; let i = 0; while (i < input.length) { let group = input[i]; if (isNumeric(group)) { while (i + 1 < input.length && isNumeric(input[i + 1])) { group = group + input[i + 1]; i++; } groups.push(parseInt(group, 10)); } else { while (i + 1 < input.length && !isNumeric(input[i + 1])) { group = group + input[i + 1]; i++; } groups.push(group); } i++; } return groups; } /** * Determine if the given value is a number */ function isNumeric(value) { return !Number.isNaN(parseInt(value, 10)); } const strategies = { alphanumeric, basic, datetime }; //#endregion export { DEFAULT_SORT_DIRECTION, SortDirection, alphanumeric, basic, datetime, strategies, transition };