Skip to content

Commit 7b57ba2

Browse files
committed
feat: respect numeric separators in natural sorting
1 parent 4fa2b3e commit 7b57ba2

File tree

2 files changed

+77
-1
lines changed

2 files changed

+77
-1
lines changed

test/sort-maps.test.ts

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -832,5 +832,71 @@ describe(RULE_NAME, () => {
832832
valid: ['new Map([[], []])', 'new Map()'],
833833
invalid: [],
834834
})
835+
836+
ruleTester.run(
837+
`${RULE_NAME}: respect numeric separators with natural sorting`,
838+
rule,
839+
{
840+
valid: [
841+
{
842+
code: dedent`
843+
new Map([
844+
[1, "first"],
845+
[2, "second"],
846+
[3, "third"],
847+
[100, "hundredth"],
848+
[1_000, "thousandth"],
849+
[1_000_000, "millionth"]
850+
])
851+
`,
852+
options: [
853+
{
854+
type: 'natural',
855+
order: 'asc',
856+
},
857+
],
858+
},
859+
],
860+
invalid: [
861+
{
862+
code: dedent`
863+
new Map([
864+
[1, "first"],
865+
[2, "second"],
866+
[3, "third"],
867+
[1_000, "thousandth"],
868+
[100, "hundredth"],
869+
[1_000_000, "millionth"]
870+
])
871+
`,
872+
output: dedent`
873+
new Map([
874+
[1, "first"],
875+
[2, "second"],
876+
[3, "third"],
877+
[100, "hundredth"],
878+
[1_000, "thousandth"],
879+
[1_000_000, "millionth"]
880+
])
881+
`,
882+
options: [
883+
{
884+
type: 'natural',
885+
order: 'asc',
886+
},
887+
],
888+
errors: [
889+
{
890+
messageId: 'unexpectedMapElementsOrder',
891+
data: {
892+
left: '1_000',
893+
right: '100',
894+
},
895+
},
896+
],
897+
},
898+
],
899+
},
900+
)
835901
})
836902
})

utils/compare.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,18 @@ export let compare = (
2828
sortingFunction = (aNode, bNode) =>
2929
formatString(aNode.name).localeCompare(formatString(bNode.name))
3030
} else if (options.type === 'natural') {
31+
let prepareNumeric = (string: string) => {
32+
let formattedNumberPattern = /^[+-]?[\d ,_]+(\.[\d ,_]+)?$/
33+
if (formattedNumberPattern.test(string)) {
34+
return string.replaceAll(/[ ,_]/g, '')
35+
}
36+
return string
37+
}
3138
sortingFunction = (aNode, bNode) =>
32-
naturalCompare(formatString(aNode.name), formatString(bNode.name))
39+
naturalCompare(
40+
prepareNumeric(formatString(aNode.name)),
41+
prepareNumeric(formatString(bNode.name)),
42+
)
3343
} else {
3444
sortingFunction = (aNode, bNode) => {
3545
let aSize = aNode.size

0 commit comments

Comments
 (0)