Skip to content

Commit

Permalink
feat: respect numeric separators in natural sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
azat-io committed Jul 22, 2024
1 parent 4fa2b3e commit 7b57ba2
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 1 deletion.
66 changes: 66 additions & 0 deletions test/sort-maps.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -832,5 +832,71 @@ describe(RULE_NAME, () => {
valid: ['new Map([[], []])', 'new Map()'],
invalid: [],
})

ruleTester.run(
`${RULE_NAME}: respect numeric separators with natural sorting`,
rule,
{
valid: [
{
code: dedent`
new Map([
[1, "first"],
[2, "second"],
[3, "third"],
[100, "hundredth"],
[1_000, "thousandth"],
[1_000_000, "millionth"]
])
`,
options: [
{
type: 'natural',
order: 'asc',
},
],
},
],
invalid: [
{
code: dedent`
new Map([
[1, "first"],
[2, "second"],
[3, "third"],
[1_000, "thousandth"],
[100, "hundredth"],
[1_000_000, "millionth"]
])
`,
output: dedent`
new Map([
[1, "first"],
[2, "second"],
[3, "third"],
[100, "hundredth"],
[1_000, "thousandth"],
[1_000_000, "millionth"]
])
`,
options: [
{
type: 'natural',
order: 'asc',
},
],
errors: [
{
messageId: 'unexpectedMapElementsOrder',
data: {
left: '1_000',
right: '100',
},
},
],
},
],
},
)
})
})
12 changes: 11 additions & 1 deletion utils/compare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,18 @@ export let compare = (
sortingFunction = (aNode, bNode) =>
formatString(aNode.name).localeCompare(formatString(bNode.name))
} else if (options.type === 'natural') {
let prepareNumeric = (string: string) => {
let formattedNumberPattern = /^[+-]?[\d ,_]+(\.[\d ,_]+)?$/
if (formattedNumberPattern.test(string)) {
return string.replaceAll(/[ ,_]/g, '')
}
return string
}
sortingFunction = (aNode, bNode) =>
naturalCompare(formatString(aNode.name), formatString(bNode.name))
naturalCompare(
prepareNumeric(formatString(aNode.name)),
prepareNumeric(formatString(bNode.name)),
)
} else {
sortingFunction = (aNode, bNode) => {
let aSize = aNode.size
Expand Down

0 comments on commit 7b57ba2

Please sign in to comment.