Skip to content

Instantly share code, notes, and snippets.

@connebs
Created September 27, 2024 03:39
Show Gist options
  • Select an option

  • Save connebs/e36d92cc6f6122fce9b58085059762ca to your computer and use it in GitHub Desktop.

Select an option

Save connebs/e36d92cc6f6122fce9b58085059762ca to your computer and use it in GitHub Desktop.
A Better (case-sensitive) Natural Sort
const numericRegex = /^\d+/;
export function naturalSortCaseSensitive(a: string, b: string) {
let aIndex = 0;
let bIndex = 0;
while (aIndex < Math.max(a.length, b.length)) {
// if either slice is a number, use regex to find the entire number and compare
const aNumericMatch = a.slice(aIndex).match(numericRegex);
const bNumericMatch = b.slice(bIndex).match(numericRegex);
if (aNumericMatch && !bNumericMatch) return -1;
if (!aNumericMatch && bNumericMatch) return 1;
if (aNumericMatch && bNumericMatch) {
const aNumber = parseInt(aNumericMatch[0]);
const bNumber = parseInt(bNumericMatch[0]);
if (aNumber > bNumber) return 1;
if (aNumber < bNumber) return -1;
aIndex += aNumericMatch[0].length;
bIndex += bNumericMatch[0].length;
}
// otherwise just compare characters directly
const aChar = a[aIndex];
const bChar = b[bIndex];
if (aChar && !bChar) return 1;
if (!aChar && bChar) return -1;
if (aChar !== bChar) return aChar.charCodeAt(0) - bChar.charCodeAt(0);
aIndex++;
bIndex++;
}
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment