Skip to content
This repository was archived by the owner on Jul 26, 2025. It is now read-only.

Commit 810c368

Browse files
committed
feat: implement sortByColumnRow
1 parent ad97cb8 commit 810c368

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/utils/geometry/__tests__/points.test.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { normalize } from '../points';
1+
import { normalize, sortByColumnRow } from '../points';
22

33
describe('normalize', () => {
44
it('simple numbers', () => {
@@ -10,3 +10,23 @@ describe('normalize', () => {
1010
expect(normalize(point)).toStrictEqual({ column: 6 / 10, row: 8 / 10 });
1111
});
1212
});
13+
14+
test('sort points', () => {
15+
const points = [
16+
{ row: 0, column: 0 },
17+
{ row: 0, column: 1 },
18+
{ row: 1, column: 0 },
19+
{ row: 0, column: -1 },
20+
{ row: 0, column: 0 },
21+
{ row: -1, column: 0 },
22+
];
23+
const sorted = sortByColumnRow(points);
24+
expect(sorted).toStrictEqual([
25+
{ row: 0, column: -1 },
26+
{ row: -1, column: 0 },
27+
{ row: 0, column: 0 },
28+
{ row: 0, column: 0 },
29+
{ row: 1, column: 0 },
30+
{ row: 0, column: 1 },
31+
]);
32+
});

src/utils/geometry/points.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,17 @@ export function dot(p1: Point, p2: Point) {
9393
export function round(point: Point): Point {
9494
return { column: Math.round(point.column), row: Math.round(point.row) };
9595
}
96+
97+
/**
98+
* Sort an array of points by column then row.
99+
*
100+
* @param points - Array of points to sort.
101+
* @returns Sorted points.
102+
*/
103+
export function sortByColumnRow(points: Point[]): Point[] {
104+
return points.slice().sort((point1, point2) => {
105+
if (point1.column < point2.column) return -1;
106+
if (point1.column > point2.column) return 1;
107+
return point1.row - point2.row;
108+
});
109+
}

0 commit comments

Comments
 (0)