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.

79 lines
2.3 KiB

  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. var 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. var lineA = mappingA.generatedLine;
  15. var lineB = mappingB.generatedLine;
  16. var columnA = mappingA.generatedColumn;
  17. var 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 neglibable overhead in general
  24. * case for a large speedup in case of mappings being added in order.
  25. */
  26. function MappingList() {
  27. this._array = [];
  28. this._sorted = true;
  29. // Serves as infimum
  30. this._last = {generatedLine: -1, generatedColumn: 0};
  31. }
  32. /**
  33. * Iterate through internal items. This method takes the same arguments that
  34. * `Array.prototype.forEach` takes.
  35. *
  36. * NOTE: The order of the mappings is NOT guaranteed.
  37. */
  38. MappingList.prototype.unsortedForEach =
  39. function MappingList_forEach(aCallback, aThisArg) {
  40. this._array.forEach(aCallback, aThisArg);
  41. };
  42. /**
  43. * Add the given source mapping.
  44. *
  45. * @param Object aMapping
  46. */
  47. MappingList.prototype.add = function MappingList_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. MappingList.prototype.toArray = function MappingList_toArray() {
  66. if (!this._sorted) {
  67. this._array.sort(util.compareByGeneratedPositionsInflated);
  68. this._sorted = true;
  69. }
  70. return this._array;
  71. };
  72. exports.MappingList = MappingList;