You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.2 KiB

4 years ago
  1. /* -*- Mode: js; js-indent-level: 2; -*- */
  2. /*
  3. * Copyright 2014 Mozilla Foundation and contributors
  4. * Licensed under the New BSD license. See LICENSE or:
  5. * http://opensource.org/licenses/BSD-3-Clause
  6. */
  7. const util = require("./util");
  8. /**
  9. * Determine whether mappingB is after mappingA with respect to generated
  10. * position.
  11. */
  12. function generatedPositionAfter(mappingA, mappingB) {
  13. // Optimized for most common case
  14. const lineA = mappingA.generatedLine;
  15. const lineB = mappingB.generatedLine;
  16. const columnA = mappingA.generatedColumn;
  17. const columnB = mappingB.generatedColumn;
  18. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  19. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  20. }
  21. /**
  22. * A data structure to provide a sorted view of accumulated mappings in a
  23. * performance conscious manner. It trades a negligible overhead in general
  24. * case for a large speedup in case of mappings being added in order.
  25. */
  26. class MappingList {
  27. constructor() {
  28. this._array = [];
  29. this._sorted = true;
  30. // Serves as infimum
  31. this._last = {generatedLine: -1, generatedColumn: 0};
  32. }
  33. /**
  34. * Iterate through internal items. This method takes the same arguments that
  35. * `Array.prototype.forEach` takes.
  36. *
  37. * NOTE: The order of the mappings is NOT guaranteed.
  38. */
  39. unsortedForEach(aCallback, aThisArg) {
  40. this._array.forEach(aCallback, aThisArg);
  41. }
  42. /**
  43. * Add the given source mapping.
  44. *
  45. * @param Object aMapping
  46. */
  47. add(aMapping) {
  48. if (generatedPositionAfter(this._last, aMapping)) {
  49. this._last = aMapping;
  50. this._array.push(aMapping);
  51. } else {
  52. this._sorted = false;
  53. this._array.push(aMapping);
  54. }
  55. }
  56. /**
  57. * Returns the flat, sorted array of mappings. The mappings are sorted by
  58. * generated position.
  59. *
  60. * WARNING: This method returns internal data without copying, for
  61. * performance. The return value must NOT be mutated, and should be treated as
  62. * an immutable borrow. If you want to take ownership, you must make your own
  63. * copy.
  64. */
  65. toArray() {
  66. if (!this._sorted) {
  67. this._array.sort(util.compareByGeneratedPositionsInflated);
  68. this._sorted = true;
  69. }
  70. return this._array;
  71. }
  72. }
  73. exports.MappingList = MappingList;