sort.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { COLUMN } from './sourcemap-segment';
  2. import type { SourceMapSegment } from './sourcemap-segment';
  3. export default function maybeSort(
  4. mappings: SourceMapSegment[][],
  5. owned: boolean,
  6. ): SourceMapSegment[][] {
  7. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  8. if (unsortedIndex === mappings.length) return mappings;
  9. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  10. // not, we do not want to modify the consumer's input array.
  11. if (!owned) mappings = mappings.slice();
  12. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  13. mappings[i] = sortSegments(mappings[i], owned);
  14. }
  15. return mappings;
  16. }
  17. function nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {
  18. for (let i = start; i < mappings.length; i++) {
  19. if (!isSorted(mappings[i])) return i;
  20. }
  21. return mappings.length;
  22. }
  23. function isSorted(line: SourceMapSegment[]): boolean {
  24. for (let j = 1; j < line.length; j++) {
  25. if (line[j][COLUMN] < line[j - 1][COLUMN]) {
  26. return false;
  27. }
  28. }
  29. return true;
  30. }
  31. function sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {
  32. if (!owned) line = line.slice();
  33. return line.sort(sortComparator);
  34. }
  35. function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {
  36. return a[COLUMN] - b[COLUMN];
  37. }