Skip to content

Commit

Permalink
feat: add natural sorting helper
Browse files Browse the repository at this point in the history
  • Loading branch information
snickbit committed Jul 1, 2023
1 parent 8adb8fc commit 55fdb2c
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions packages/utilities/src/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,3 +176,22 @@ export function wordWrap(text: string, characters: number, padding?: number): st
}
return lines.map(line => padString(line, padding)).join('\n')
}

/**
* Compare two strings using a "natural order" algorithm
* @param {string} str1
* @param {string} str2
* @param {boolean} [caseSensitive=false]
* @category Strings
*/
export function naturalSort(str1: string, str2: string, caseSensitive = false): number {
const a = caseSensitive ? str1 : str1.toLowerCase()
const b = caseSensitive ? str2 : str2.toLowerCase()

const collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: 'base'
})

return collator.compare(a, b)
}

0 comments on commit 55fdb2c

Please sign in to comment.