1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 | const NONE = Symbol("not sorted");
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | class SortableSet extends Set {
|
16 | |
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | constructor(initialIterable, defaultSort) {
|
23 | super(initialIterable);
|
24 |
|
25 | this._sortFn = defaultSort;
|
26 |
|
27 | this._lastActiveSortFn = NONE;
|
28 |
|
29 | this._cache = undefined;
|
30 |
|
31 | this._cacheOrderIndependent = undefined;
|
32 | }
|
33 |
|
34 | |
35 |
|
36 |
|
37 |
|
38 | add(value) {
|
39 | this._lastActiveSortFn = NONE;
|
40 | this._invalidateCache();
|
41 | this._invalidateOrderedCache();
|
42 | super.add(value);
|
43 | return this;
|
44 | }
|
45 |
|
46 | |
47 |
|
48 |
|
49 |
|
50 | delete(value) {
|
51 | this._invalidateCache();
|
52 | this._invalidateOrderedCache();
|
53 | return super.delete(value);
|
54 | }
|
55 |
|
56 | |
57 |
|
58 |
|
59 | clear() {
|
60 | this._invalidateCache();
|
61 | this._invalidateOrderedCache();
|
62 | return super.clear();
|
63 | }
|
64 |
|
65 | |
66 |
|
67 |
|
68 |
|
69 |
|
70 | sortWith(sortFn) {
|
71 | if (this.size <= 1 || sortFn === this._lastActiveSortFn) {
|
72 |
|
73 | return;
|
74 | }
|
75 |
|
76 | const sortedArray = Array.from(this).sort(sortFn);
|
77 | super.clear();
|
78 | for (let i = 0; i < sortedArray.length; i += 1) {
|
79 | super.add(sortedArray[i]);
|
80 | }
|
81 | this._lastActiveSortFn = sortFn;
|
82 | this._invalidateCache();
|
83 | }
|
84 |
|
85 | sort() {
|
86 | this.sortWith(this._sortFn);
|
87 | return this;
|
88 | }
|
89 |
|
90 | |
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 | getFromCache(fn) {
|
97 | if (this._cache === undefined) {
|
98 | this._cache = new Map();
|
99 | } else {
|
100 | const result = this._cache.get(fn);
|
101 | const data = (result);
|
102 | if (data !== undefined) {
|
103 | return data;
|
104 | }
|
105 | }
|
106 | const newData = fn(this);
|
107 | this._cache.set(fn, newData);
|
108 | return newData;
|
109 | }
|
110 |
|
111 | |
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 | getFromUnorderedCache(fn) {
|
118 | if (this._cacheOrderIndependent === undefined) {
|
119 | this._cacheOrderIndependent = new Map();
|
120 | } else {
|
121 | const result = this._cacheOrderIndependent.get(fn);
|
122 | const data = (result);
|
123 | if (data !== undefined) {
|
124 | return data;
|
125 | }
|
126 | }
|
127 | const newData = fn(this);
|
128 | this._cacheOrderIndependent.set(fn, newData);
|
129 | return newData;
|
130 | }
|
131 |
|
132 | |
133 |
|
134 |
|
135 |
|
136 | _invalidateCache() {
|
137 | if (this._cache !== undefined) {
|
138 | this._cache.clear();
|
139 | }
|
140 | }
|
141 |
|
142 | |
143 |
|
144 |
|
145 |
|
146 | _invalidateOrderedCache() {
|
147 | if (this._cacheOrderIndependent !== undefined) {
|
148 | this._cacheOrderIndependent.clear();
|
149 | }
|
150 | }
|
151 |
|
152 | |
153 |
|
154 |
|
155 | toJSON() {
|
156 | return Array.from(this);
|
157 | }
|
158 | }
|
159 |
|
160 | module.exports = SortableSet;
|