Skip to content

Commit

Permalink
fix: Ignore whitespaces in node names
Browse files Browse the repository at this point in the history
  • Loading branch information
hugop95 authored Sep 26, 2024
1 parent c18cb4d commit 7a0a96c
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 8 deletions.
14 changes: 14 additions & 0 deletions test/sort-intersection-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1439,5 +1439,19 @@ describe(ruleName, () => {
],
},
)

ruleTester.run(`${ruleName}: should ignore whitespaces`, rule, {
valid: [
{
code: dedent`
type T =
{ a: string } &
{ b: string }
`,
options: [{}],
},
],
invalid: [],
})
})
})
14 changes: 14 additions & 0 deletions test/sort-union-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1471,5 +1471,19 @@ describe(ruleName, () => {
],
},
)

ruleTester.run(`${ruleName}: should ignore whitespaces`, rule, {
valid: [
{
code: dedent`
type T =
{ a: string } |
{ b: string }
`,
options: [{}],
},
],
invalid: [],
})
})
})
21 changes: 13 additions & 8 deletions utils/compare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,11 @@ export let compare = (
): number => {
let orderCoefficient = options.order === 'asc' ? 1 : -1
let sortingFunction: (a: SortingNode, b: SortingNode) => number

let formatString =
options.type === 'line-length' || !options.ignoreCase
? (string: string) => string
: (string: string) => string.toLowerCase()

let nodeValueGetter =
options.nodeValueGetter ?? ((node: SortingNode) => node.name)

if (options.type === 'alphabetical') {
let formatString = getFormatStringFunc(!!options.ignoreCase)
sortingFunction = (aNode, bNode) =>
formatString(nodeValueGetter(aNode)).localeCompare(
formatString(nodeValueGetter(bNode)),
Expand All @@ -59,11 +54,13 @@ export let compare = (
}
return string
}
sortingFunction = (aNode, bNode) =>
naturalCompare(
sortingFunction = (aNode, bNode) => {
let formatString = getFormatStringFunc(!!options.ignoreCase)
return naturalCompare(
prepareNumeric(formatString(nodeValueGetter(aNode))),
prepareNumeric(formatString(nodeValueGetter(bNode))),
)
}
} else {
sortingFunction = (aNode, bNode) => {
let aSize = aNode.size
Expand All @@ -90,3 +87,11 @@ export let compare = (

return orderCoefficient * sortingFunction(a, b)
}

let getFormatStringFunc = (ignoreCase: boolean) => (value: string) => {
let valueToCompare = value
if (ignoreCase) {
valueToCompare = valueToCompare.toLowerCase()
}
return valueToCompare.replaceAll(/\s/g, '')
}

0 comments on commit 7a0a96c

Please sign in to comment.