diff --git a/src/language/__tests__/location-test.ts b/src/language/__tests__/location-test.ts index 0ffea1a067..bd9d2e3485 100644 --- a/src/language/__tests__/location-test.ts +++ b/src/language/__tests__/location-test.ts @@ -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'; @@ -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); + } + }); }); diff --git a/src/language/location.ts b/src/language/location.ts index 42ac18e935..24a3975b45 100644 --- a/src/language/location.ts +++ b/src/language/location.ts @@ -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) {