SortableSet.js 923B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. module.exports = class SortableSet extends Set {
  3. constructor(initialIterable, defaultSort) {
  4. super(initialIterable);
  5. this._sortFn = defaultSort;
  6. this._lastActiveSortFn = null;
  7. }
  8. /**
  9. * @param {any} value - value to add to set
  10. * @returns {SortableSet} - returns itself
  11. */
  12. add(value) {
  13. this._lastActiveSortFn = null;
  14. super.add(value);
  15. return this;
  16. }
  17. /**
  18. * @param {Function} sortFn - function to sort the set
  19. * @returns {void}
  20. */
  21. sortWith(sortFn) {
  22. if(this.size === 0 || sortFn === this._lastActiveSortFn) {
  23. // already sorted - nothing to do
  24. return;
  25. }
  26. const sortedArray = Array.from(this).sort(sortFn);
  27. super.clear();
  28. for(let i = 0; i < sortedArray.length; i += 1) {
  29. this.add(sortedArray[i]);
  30. }
  31. this._lastActiveSortFn = sortFn;
  32. }
  33. /**
  34. * @returns {void}
  35. */
  36. sort() {
  37. this.sortWith(this._sortFn);
  38. }
  39. };