Skip to content

Commit

Permalink
fix(format): use localeCompare for sorting
Browse files Browse the repository at this point in the history
Closes #206
Closes #214
  • Loading branch information
evaliyev authored and JamieMason committed Jul 24, 2024
1 parent ee54fd7 commit e8c9bd3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
18 changes: 11 additions & 7 deletions src/bin-format/format.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,21 +128,25 @@ describe('sortAz', () => {
it('sorts object properties alphabetically by key', async () => {
const scenario = createScenario({
'.syncpackrc': {
sortAz: ['scripts'],
sortAz: ['dependencies'],
},
'package.json': {
name: 'a',
scripts: {
B: '',
A: '',
dependencies: {
'B': '',
'@B': '',
'1B': '',
'A': '',
'@A': '',
'1A': ''
},
},
})();

await Effect.runPromiseExit(format(scenario));

const packages: any = scenario.readPackages();
expect(Object.keys(packages.a.scripts)).toEqual(['A', 'B']);
expect(Object.keys(packages.a.dependencies)).toEqual(['@A', '@B', '1A', '1B', 'A', 'B']);
expect(scenario.io.process.exit).not.toHaveBeenCalled();
});

Expand All @@ -153,15 +157,15 @@ describe('sortAz', () => {
},
'package.json': {
name: 'a',
keywords: ['B', 'A'],
keywords: ['B', '@B', '1B', 'A', '@A', '1A'],
},
})();

await Effect.runPromiseExit(format(scenario));

expect(scenario.readPackages()).toHaveProperty('a', {
name: 'a',
keywords: ['A', 'B'],
keywords: ['@A', '@B', '1A', '1B', 'A', 'B'],
});
expect(scenario.io.process.exit).not.toHaveBeenCalled();
});
Expand Down
8 changes: 5 additions & 3 deletions src/bin-format/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type { Io } from '../io/index.js';
import { IoTag } from '../io/index.js';
import { writeIfChanged } from '../io/write-if-changed.js';
import { withLogger } from '../lib/with-logger.js';
import type { PackageJson } from '../get-package-json-files/package-json-file.js';

interface Input {
io: Io;
Expand Down Expand Up @@ -117,10 +118,11 @@ function sortObject(sortedKeys: string[] | Set<string>, obj: Record<string, unkn
});
}

function sortAlphabetically(value: unknown): void {
function sortAlphabetically(value: PackageJson[keyof PackageJson]): void {
const localeComparison = (a: string, b: string) => a.localeCompare(b);
if (isArray(value)) {
value.sort();
value.sort(localeComparison);
} else if (isObject(value)) {
sortObject(Object.keys(value).sort(), value);
sortObject(Object.keys(value).sort(localeComparison), value);
}
}

0 comments on commit e8c9bd3

Please sign in to comment.