-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynMapReducer.ts
365 lines (302 loc) · 10.4 KB
/
DynMapReducer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import {
AdapterDerived,
AdapterFilters,
AdapterSort,
DerivedAPI,
DynReducerUtils,
IndexerAPI } from '../common';
import { MapIndexer } from './MapIndexer';
import type {
IDynAdapterFilters,
IDynAdapterSort,
IDynDerivedAPI,
IDynIndexerAPI,
DynCompareFn,
DynMapData,
DynDataFilter,
DynDataHost,
DynDataSort,
DynFilterFn } from '../types';
import { DynMapReducerDerived } from './derived/DynMapReducerDerived.js';
/**
* Provides a managed Map with non-destructive reducing / filtering / sorting capabilities with subscription /
* Svelte store support.
*
* @template K, T
*/
export class DynMapReducer<K, T>
{
#map: DynDataHost<Map<K, T>> = [null];
readonly #derived: AdapterDerived<Map<K, T>, K, T>;
readonly #derivedPublicAPI: DerivedAPI<Map<K, T>, K, T>;
readonly #filters: AdapterFilters<T>;
readonly #filtersData: { filters: DynDataFilter<T>[] } = { filters: [] };
readonly #index: MapIndexer<K, T>;
readonly #indexPublicAPI: IndexerAPI<K, T>;
#reversed: boolean = false;
readonly #sort: AdapterSort<T>;
#sortData: { compareFn: DynCompareFn<T> } = { compareFn: null };
#subscriptions: Function[] = [];
#destroyed = false;
/**
* Initializes DynMapReducer. Any iterable is supported for initial data. Take note that if `data` is an array it
* will be used as the host array and not copied. All non-array iterables otherwise create a new array / copy.
*
* @param {Map<K, T> | DynMapData<K, T>} [data] - Data iterable to store if array or copy otherwise.
*/
constructor(data?: Map<K, T> | DynMapData<K, T>)
{
let dataMap: Map<K, T> = void 0;
let filters: Iterable<DynFilterFn<T> | DynDataFilter<T>> = void 0;
let sort: DynCompareFn<T> | DynDataSort<T> = void 0;
if (data === null)
{
throw new TypeError(`DynMapReducer error: 'data' is not an object or Map.`);
}
if (data !== void 0 && typeof data !== 'object' && !(data as any instanceof Map))
{
throw new TypeError(`DynMapReducer error: 'data' is not an object or Map.`);
}
if (data !== void 0 && data instanceof Map)
{
dataMap = data;
}
else if (data !== void 0 && ('data' in data || 'filters' in data || 'sort' in data))
{
if (data.data !== void 0 && !(data.data instanceof Map))
{
throw new TypeError(`DynMapReducer error (DataDynMap): 'data' attribute is not a Map.`);
}
dataMap = data.data;
if (data.filters !== void 0)
{
if (DynReducerUtils.isIterable(data.filters))
{
filters = data.filters;
}
else
{
throw new TypeError(`DynMapReducer error (DataDynMap): 'filters' attribute is not iterable.`);
}
}
if (data.sort !== void 0)
{
if (typeof data.sort === 'function')
{
sort = data.sort;
}
else if (typeof data.sort === 'object' && data.sort !== null)
{
sort = data.sort;
}
else
{
throw new TypeError(
`DynMapReducer error (DataDynMap): 'sort' attribute is not a function or object.`);
}
}
}
// In the case of the main data being an array directly use the array otherwise create a copy.
if (dataMap)
{
this.#map[0] = dataMap;
}
this.#index = new MapIndexer(this.#map, this.#updateSubscribers.bind(this));
this.#indexPublicAPI = new IndexerAPI<K, T>(this.#index);
this.#filters = new AdapterFilters(this.#indexPublicAPI.update, this.#filtersData);
this.#sort = new AdapterSort(this.#indexPublicAPI.update, this.#sortData);
this.#derived = new AdapterDerived(this.#map, this.#indexPublicAPI, DynMapReducerDerived);
this.#derivedPublicAPI = new DerivedAPI<Map<K, T>, K, T>(this.#derived);
this.#index.initAdapters(this.#filtersData, this.#sortData, this.#derived);
// Add any filters and sort function defined by DataDynMap.
if (filters) { this.filters.add(...filters); }
if (sort) { this.sort.set(sort); }
// Invoke an custom initialization for child classes.
this.initialize();
}
/**
* Returns the internal data of this instance. Be careful!
*
* Note: When a map is set as data then that map is used as the internal data. If any changes are performed to the
* data externally do invoke `update` via {@link DynMapReducer.index} with `true` to recalculate the index and
* notify all subscribers.
*
* @returns {Map<K, T> | null} The internal data.
*/
get data(): Map<K, T> | null { return this.#map[0]; }
/**
* @returns {IDynDerivedAPI<Map<K, T>, K, T>} Derived public API.
*/
get derived(): IDynDerivedAPI<Map<K, T>, K, T> { return this.#derivedPublicAPI; }
/**
* @returns {IDynAdapterFilters<T>} The filters adapter.
*/
get filters(): IDynAdapterFilters<T> { return this.#filters; }
/**
* @returns {IDynIndexerAPI<K, T>} Returns the Indexer public API.
*/
get index(): IDynIndexerAPI<K, T> { return this.#indexPublicAPI; }
/**
* @returns {boolean} Returns whether this instance is destroyed.
*/
get destroyed(): boolean { return this.#destroyed; }
/**
* Gets the main data / items length.
*
* @returns {number} Main data / items length.
*/
get length(): number
{
const map = this.#map[0];
return this.#index.active ? this.#indexPublicAPI.length :
map ? map.size : 0;
}
/**
* Gets current reversed state.
*
* @returns {boolean} Reversed state.
*/
get reversed(): boolean { return this.#reversed; }
/**
* @returns {IDynAdapterSort<T>} The sort adapter.
*/
get sort(): IDynAdapterSort<T> { return this.#sort; }
/**
* Sets reversed state and notifies subscribers.
*
* @param {boolean} reversed - New reversed state.
*/
set reversed(reversed: boolean)
{
if (typeof reversed !== 'boolean')
{
throw new TypeError(`DynMapReducer.reversed error: 'reversed' is not a boolean.`);
}
this.#reversed = reversed;
this.#index.reversed = reversed;
// Recalculate index and force an update to any subscribers.
this.index.update(true);
}
/**
* Removes all derived reducers, subscriptions, and cleans up all resources.
*/
destroy()
{
if (this.#destroyed) { return; }
this.#destroyed = true;
this.#derived.destroy();
// Set the backing data to null and provide a final update.
this.#map = [null];
this.index.update(true);
// Remove all subscriptions.
this.#subscriptions.length = 0;
this.#index.destroy();
this.#filters.clear();
this.#sort.clear();
}
/**
* Provides a callback for custom reducers to initialize any data / custom configuration. This allows
* child classes to avoid implementing the constructor.
*
* @protected
*/
initialize() {}
/**
* Removes internal data and pushes new data. This does not destroy any initial array set to internal data unless
* `replace` is set to true.
*
* @param {Map<K, T> | null} data - New data to set to internal data.
*
* @param {boolean} [replace=false] - New data to set to internal data.
*/
setData(data: Map<K, T> | null, replace: boolean = false)
{
if (data !== null && !(data instanceof Map))
{
throw new TypeError(`DynMapReducer.setData error: 'data' is not iterable.`);
}
if (typeof replace !== 'boolean')
{
throw new TypeError(`DynMapReducer.setData error: 'replace' is not a boolean.`);
}
const map = this.#map[0];
// If the array isn't defined or 'replace' is true then replace internal data with new array or create an array
// from an iterable.
if (!(map instanceof Map) || replace)
{
this.#map[0] = data instanceof Map ? data : null;
}
else if (data instanceof Map && map instanceof Map)
{
// Create a set of all current entry IDs.
const removeKeySet = new Set(map.keys());
for (const key of data.keys())
{
map.set(key, data.get(key));
if (removeKeySet.has(key)) { removeKeySet.delete(key); }
}
// Remove entries that are no longer in data.
for (const key of removeKeySet) { map.delete(key); }
}
else if (data === null)
{
this.#map[0] = null;
}
// Recalculate index and force an update to any subscribers.
this.index.update(true);
}
/**
* Add a subscriber to this DynMapReducer instance.
*
* @param {(value: DynMapReducer<K, T>) => void} handler - Callback function that is invoked on update / changes.
* Receives `this` reference.
*
* @returns {() => void} Unsubscribe function.
*/
subscribe(handler: (value: DynMapReducer<K, T>) => void): () => void
{
this.#subscriptions.push(handler); // add handler to the array of subscribers
handler(this); // call handler with current value
// Return unsubscribe function.
return () =>
{
const index = this.#subscriptions.findIndex((sub) => sub === handler);
if (index >= 0) { this.#subscriptions.splice(index, 1); }
};
}
/**
* Updates subscribers on changes.
*/
#updateSubscribers()
{
for (let cntr = 0; cntr < this.#subscriptions.length; cntr++) { this.#subscriptions[cntr](this); }
}
/**
* Provides an iterator for data stored in DynMapReducer.
*
* @returns {IterableIterator<T>}
* @yields {T}
*/
*[Symbol.iterator](): IterableIterator<T>
{
const map = this.#map[0];
if (this.#destroyed || map === null || map?.size === 0) { return; }
if (this.#index.active)
{
for (const key of this.index) { yield map.get(key); }
}
else
{
if (this.reversed)
{
// TODO: Not efficient due to creating temporary values array.
const values = [...map.values()];
for (let cntr = values.length; --cntr >= 0;) { yield values[cntr]; }
}
else
{
for (const value of map.values()) { yield value; }
}
}
}
}