Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion src/language/__tests__/location-test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it } from 'node:test';

import { expect } from 'chai';
import { assert, expect } from 'chai';

import { getLocation, getLocations } from '../location.ts';
import { Source } from '../source.ts';
Expand Down Expand Up @@ -196,4 +196,31 @@ describe('getLocations', () => {
{ line: 1, column: 2 },
]);
});

it('gets locations when Array.prototype.toSorted is unavailable', () => {
const source = new Source('a\nb\nc');
const locations = Object.freeze([
Object.freeze({ source, start: 4 }),
Object.freeze({ source, start: 0 }),
Object.freeze({ source, start: 2 }),
]);
const descriptor = Object.getOwnPropertyDescriptor(
Array.prototype,
'toSorted',
);
assert(descriptor != null);

assert(Reflect.deleteProperty(Array.prototype, 'toSorted'));
try {
expect(getLocations(locations)).to.deep.equal([
{ line: 3, column: 1 },
{ line: 1, column: 1 },
{ line: 2, column: 1 },
]);
expect(locations.map(({ start }) => start)).to.deep.equal([4, 0, 2]);
} finally {
// eslint-disable-next-line no-extend-native -- restore the removed engine method
Object.defineProperty(Array.prototype, 'toSorted', descriptor);
}
});
});
4 changes: 3 additions & 1 deletion src/language/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ export function getLocations(
let match = matches.next().value;
let line = 1;
let lastLineStart = 0;
for (const { position, index } of positions.toSorted(
// `positions` is allocated above and is not returned to the caller, so
// sorting it in place matches `toSorted` on engines without ES2023.
for (const { position, index } of positions.sort(
(a, b) => a.position - b.position,
)) {
while (match !== undefined && match.index < position) {
Expand Down