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.

100 lines
2.3 KiB

4 years ago
  1. /* -*- Mode: js; js-indent-level: 2; -*- */
  2. /*
  3. * Copyright 2011 Mozilla Foundation and contributors
  4. * Licensed under the New BSD license. See LICENSE or:
  5. * http://opensource.org/licenses/BSD-3-Clause
  6. */
  7. /**
  8. * A data structure which is a combination of an array and a set. Adding a new
  9. * member is O(1), testing for membership is O(1), and finding the index of an
  10. * element is O(1). Removing elements from the set is not supported. Only
  11. * strings are supported for membership.
  12. */
  13. class ArraySet {
  14. constructor() {
  15. this._array = [];
  16. this._set = new Map();
  17. }
  18. /**
  19. * Static method for creating ArraySet instances from an existing array.
  20. */
  21. static fromArray(aArray, aAllowDuplicates) {
  22. const set = new ArraySet();
  23. for (let i = 0, len = aArray.length; i < len; i++) {
  24. set.add(aArray[i], aAllowDuplicates);
  25. }
  26. return set;
  27. }
  28. /**
  29. * Return how many unique items are in this ArraySet. If duplicates have been
  30. * added, than those do not count towards the size.
  31. *
  32. * @returns Number
  33. */
  34. size() {
  35. return this._set.size;
  36. }
  37. /**
  38. * Add the given string to this set.
  39. *
  40. * @param String aStr
  41. */
  42. add(aStr, aAllowDuplicates) {
  43. const isDuplicate = this.has(aStr);
  44. const idx = this._array.length;
  45. if (!isDuplicate || aAllowDuplicates) {
  46. this._array.push(aStr);
  47. }
  48. if (!isDuplicate) {
  49. this._set.set(aStr, idx);
  50. }
  51. }
  52. /**
  53. * Is the given string a member of this set?
  54. *
  55. * @param String aStr
  56. */
  57. has(aStr) {
  58. return this._set.has(aStr);
  59. }
  60. /**
  61. * What is the index of the given string in the array?
  62. *
  63. * @param String aStr
  64. */
  65. indexOf(aStr) {
  66. const idx = this._set.get(aStr);
  67. if (idx >= 0) {
  68. return idx;
  69. }
  70. throw new Error('"' + aStr + '" is not in the set.');
  71. }
  72. /**
  73. * What is the element at the given index?
  74. *
  75. * @param Number aIdx
  76. */
  77. at(aIdx) {
  78. if (aIdx >= 0 && aIdx < this._array.length) {
  79. return this._array[aIdx];
  80. }
  81. throw new Error("No element indexed by " + aIdx);
  82. }
  83. /**
  84. * Returns the array representation of this set (which has the proper indices
  85. * indicated by indexOf). Note that this is a copy of the internal array used
  86. * for storing the members so that no one can mess with internal state.
  87. */
  88. toArray() {
  89. return this._array.slice();
  90. }
  91. }
  92. exports.ArraySet = ArraySet;