mapping-list.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 (
  19. lineB > lineA ||
  20. (lineB == lineA && columnB >= columnA) ||
  21. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0
  22. );
  23. }
  24. /**
  25. * A data structure to provide a sorted view of accumulated mappings in a
  26. * performance conscious manner. It trades a negligible overhead in general
  27. * case for a large speedup in case of mappings being added in order.
  28. */
  29. class MappingList {
  30. constructor() {
  31. this._array = [];
  32. this._sorted = true;
  33. // Serves as infimum
  34. this._last = { generatedLine: -1, generatedColumn: 0 };
  35. }
  36. /**
  37. * Iterate through internal items. This method takes the same arguments that
  38. * `Array.prototype.forEach` takes.
  39. *
  40. * NOTE: The order of the mappings is NOT guaranteed.
  41. */
  42. unsortedForEach(aCallback, aThisArg) {
  43. this._array.forEach(aCallback, aThisArg);
  44. }
  45. /**
  46. * Add the given source mapping.
  47. *
  48. * @param Object aMapping
  49. */
  50. add(aMapping) {
  51. if (generatedPositionAfter(this._last, aMapping)) {
  52. this._last = aMapping;
  53. this._array.push(aMapping);
  54. } else {
  55. this._sorted = false;
  56. this._array.push(aMapping);
  57. }
  58. }
  59. /**
  60. * Returns the flat, sorted array of mappings. The mappings are sorted by
  61. * generated position.
  62. *
  63. * WARNING: This method returns internal data without copying, for
  64. * performance. The return value must NOT be mutated, and should be treated as
  65. * an immutable borrow. If you want to take ownership, you must make your own
  66. * copy.
  67. */
  68. toArray() {
  69. if (!this._sorted) {
  70. this._array.sort(util.compareByGeneratedPositionsInflated);
  71. this._sorted = true;
  72. }
  73. return this._array;
  74. }
  75. }
  76. exports.MappingList = MappingList;