Apply module bundling
[platform/framework/web/wrtjs.git] / node_modules / @jridgewell / trace-mapping / src / sort.ts
1 import { COLUMN } from './sourcemap-segment';
2
3 import type { SourceMapSegment } from './sourcemap-segment';
4
5 export default function maybeSort(
6   mappings: SourceMapSegment[][],
7   owned: boolean,
8 ): SourceMapSegment[][] {
9   const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
10   if (unsortedIndex === mappings.length) return mappings;
11
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();
15
16   for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
17     mappings[i] = sortSegments(mappings[i], owned);
18   }
19   return mappings;
20 }
21
22 function nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {
23   for (let i = start; i < mappings.length; i++) {
24     if (!isSorted(mappings[i])) return i;
25   }
26   return mappings.length;
27 }
28
29 function isSorted(line: SourceMapSegment[]): boolean {
30   for (let j = 1; j < line.length; j++) {
31     if (line[j][COLUMN] < line[j - 1][COLUMN]) {
32       return false;
33     }
34   }
35   return true;
36 }
37
38 function sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {
39   if (!owned) line = line.slice();
40   return line.sort(sortComparator);
41 }
42
43 function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {
44   return a[COLUMN] - b[COLUMN];
45 }