1 import { COLUMN } from './sourcemap-segment';
3 import type { SourceMapSegment } from './sourcemap-segment';
5 export default function maybeSort(
6 mappings: SourceMapSegment[][],
8 ): SourceMapSegment[][] {
9 const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
10 if (unsortedIndex === mappings.length) return mappings;
12 // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
13 // not, we do not want to modify the consumer's input array.
14 if (!owned) mappings = mappings.slice();
16 for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
17 mappings[i] = sortSegments(mappings[i], owned);
22 function nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {
23 for (let i = start; i < mappings.length; i++) {
24 if (!isSorted(mappings[i])) return i;
26 return mappings.length;
29 function isSorted(line: SourceMapSegment[]): boolean {
30 for (let j = 1; j < line.length; j++) {
31 if (line[j][COLUMN] < line[j - 1][COLUMN]) {
38 function sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {
39 if (!owned) line = line.slice();
40 return line.sort(sortComparator);
43 function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {
44 return a[COLUMN] - b[COLUMN];