Skip to content

Instantly share code, notes, and snippets.

@randName
Created January 20, 2026 02:59
Show Gist options
  • Select an option

  • Save randName/496d3f6b02a160395f6c15cbe7996f08 to your computer and use it in GitHub Desktop.

Select an option

Save randName/496d3f6b02a160395f6c15cbe7996f08 to your computer and use it in GitHub Desktop.
sorting of strings containing numbers
/** @param {number} c charCode */
const isNumber = (c) => c > 47 && c < 58 // digits 0 - 9 have codes 48 to 57
/**
* @param {string} a
* @param {string} b
*/
export function compare(a, b) {
const minLen = Math.min(a.length, b.length)
for (let i = 0; i < minLen; ++i) {
const aCode = a.charCodeAt(i)
const bCode = b.charCodeAt(i)
// both are numbers, extract and compare as numbers
if (isNumber(aCode) && isNumber(bCode)) {
let aEnd = i + 1
let bEnd = i + 1
// find the end of the number
while (isNumber(a.charCodeAt(aEnd))) ++aEnd
while (isNumber(b.charCodeAt(bEnd))) ++bEnd
return Number(a.slice(i, aEnd)) - Number(b.slice(i, bEnd))
}
// same char, continue checking along the string
if (aCode === bCode) continue
// otherwise, compare the character codes directly
return aCode - bCode
}
// same prefix, shorter string should come first
return a.length - b.length
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment