123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- "use strict";
- class SortableSet extends Set {
-
- constructor(initialIterable, defaultSort) {
- super(initialIterable);
-
- this._sortFn = defaultSort;
-
- this._lastActiveSortFn = null;
-
- this._cache = undefined;
-
- this._cacheOrderIndependent = undefined;
- }
-
- add(value) {
- this._lastActiveSortFn = null;
- this._invalidateCache();
- this._invalidateOrderedCache();
- super.add(value);
- return this;
- }
-
- delete(value) {
- this._invalidateCache();
- this._invalidateOrderedCache();
- return super.delete(value);
- }
-
- clear() {
- this._invalidateCache();
- this._invalidateOrderedCache();
- return super.clear();
- }
-
- sortWith(sortFn) {
- if (this.size <= 1 || sortFn === this._lastActiveSortFn) {
-
- return;
- }
- const sortedArray = Array.from(this).sort(sortFn);
- super.clear();
- for (let i = 0; i < sortedArray.length; i += 1) {
- super.add(sortedArray[i]);
- }
- this._lastActiveSortFn = sortFn;
- this._invalidateCache();
- }
- sort() {
- this.sortWith(this._sortFn);
- }
-
- getFromCache(fn) {
- if (this._cache === undefined) {
- this._cache = new Map();
- } else {
- const data = this._cache.get(fn);
- if (data !== undefined) {
- return data;
- }
- }
- const newData = fn(this);
- this._cache.set(fn, newData);
- return newData;
- }
-
- getFromUnorderedCache(fn) {
- if (this._cacheOrderIndependent === undefined) {
- this._cacheOrderIndependent = new Map();
- } else {
- const data = this._cacheOrderIndependent.get(fn);
- if (data !== undefined) {
- return data;
- }
- }
- const newData = fn(this);
- this._cacheOrderIndependent.set(fn, newData);
- return newData;
- }
-
- _invalidateCache() {
- if (this._cache !== undefined) {
- this._cache.clear();
- }
- }
-
- _invalidateOrderedCache() {
- if (this._cacheOrderIndependent !== undefined) {
- this._cacheOrderIndependent.clear();
- }
- }
- }
- module.exports = SortableSet;
|