This repository has been archived by the owner on Oct 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Collection.ts
459 lines (385 loc) Β· 13.6 KB
/
Collection.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/**
* Copyright (c) Noelware
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Represents a predicate function for any mutable methods
*/
export type Predicate<ThisArg, Value, Index, Key, ReturnAs> = (
this: ThisArg,
value: Value,
index: Index,
key: Key
) => ReturnAs;
/**
* Represents a predicate function for [[Collection#reduce]]
*/
export type ReducePredicate<ThisArg, Current, Acc, ReturnAs> = (this: ThisArg, acc: Acc, current: Current) => ReturnAs;
/**
* Same as [[Predicate]] but with no this context binded.
*/
export type UndetailedPredicate<Value, Index, Key, ReturnAs> = (value: Value, index: Index, key: Key) => ReturnAs;
/**
* Same as [[Predicate]] but without `index` and `key` arguments
*/
export type MinimalPredicate<ThisArg, Value, ReturnAs> = (this: ThisArg, value: Value) => ReturnAs;
/**
* Same as [[Predicate]] but with no this context binded and without `index` or `key` arguments
*/
export type UndetailedMinimalPredicate<Value, ReturnAs> = (value: Value) => ReturnAs;
/**
* Represents a class to hold key-value pairs using [[Collection]]. This is a extension
* of [Map] to add Array-like functions and a update builder.
*
* @template K The key structure for this [[Collection]]
* @template V The value structure for this [[Collection]]
*/
export class Collection<K, V = unknown> extends Map<K, V> {
protected _sweepInterval?: NodeJS.Timer;
public ['constructor']: typeof Collection;
/** Returns if this [[`Collection`]] is empty or not */
get empty() {
return this.size === 0;
}
/**
* Use a predicate function to filter out values and return a new Array of the values
* that resolved true in the predicate function. Use Collection#filterKeys to filter
* out any keys if needed.
*
* @param predicate The predicate function to filter out
* @param thisArg An additional `this` context if needed
* @returns A new Array of the values that returned `true` in the predicate function
*/
filter<ThisArg = Collection<K, V>>(predicate: Predicate<ThisArg, V, number, K, boolean>, thisArg?: ThisArg) {
let func: UndetailedPredicate<V, number, K, boolean>;
if (thisArg !== undefined) func = predicate.bind(thisArg);
else func = predicate.bind(<any>this);
const results: V[] = [];
let i = -1;
for (const [key, value] of this.entries()) {
if (func(value, i++, key)) results.push(value);
}
return results;
}
/**
* Use a predicate function to filter out keys and return a new Array of the keys
* that resolved true in the predicate function. Use Collection#filter to filter out
* any values from this [[`Collection`]].
*
* @param predicate The predicate function to filter out
* @param thisArg An additional `this` context if needed
* @returns A new Array of the values that returned `true` in the predicate function
*/
filterKeys<ThisArg = Collection<K, V>>(predicate: Predicate<ThisArg, V, number, K, boolean>, thisArg?: ThisArg) {
let func: UndetailedPredicate<V, number, K, boolean>;
if (thisArg !== undefined) func = predicate.bind(thisArg);
else func = predicate.bind(<any>this);
const results: K[] = [];
let i = -1;
for (const [key, value] of this.entries()) {
if (func(value, i++, key)) results.push(key);
}
return results;
}
/**
* Use a predicate function to map anything into a new array
* @param predicate The predicate function to map out and return a new array
* @param thisArg An additional `this` context if needed
* @returns A new Array of the values from that function
*/
map<S, ThisArg = Collection<K, V>>(predicate: Predicate<ThisArg, V, number, K, S>, thisArg?: ThisArg) {
let func: UndetailedPredicate<V, number, K, S>;
if (thisArg !== undefined) func = predicate.bind(thisArg);
else func = predicate.bind(<any>this);
const results: S[] = [];
let i = -1;
for (const [key, value] of this.entries()) {
results.push(func(value, ++i, key));
}
return results;
}
/**
* Returns a random value from the collection
* @returns A random value or `null` if the collection is empty
*/
random() {
if (this.empty) return null;
const iterable = Array.from(this.values());
return iterable[Math.floor(Math.random() * iterable.length)];
}
/**
* Reduce the collection and return a new initial value
* @param predicate The predicate function
* @param initialValue The initial value
*/
reduce<S>(predicate: ReducePredicate<Collection<K, V>, V, S, S>, initialValue?: S) {
const iterable = this.values();
let value!: V;
let res: S = initialValue === undefined ? iterable.next().value : initialValue;
const func = predicate.bind(this);
while ((value = iterable.next().value) !== undefined) res = func(res, value);
return res;
}
/**
* Returns the first element in the collection
*/
first(): V | undefined;
/**
* Returns an Array of the values from the correspondant `amount`
* @param amount The amount to fetch from
*/
first(amount: number): V[];
/**
* Returns the first element in the collection or an Array of the values from the correspondant `amount`
* @param amount The amount to fetch from
*/
first(amount?: number): V | V[] | undefined {
if (typeof amount === 'undefined') {
const iterable = this.values();
return iterable.next().value;
}
if (amount < 0) return this.last(amount! * -1);
amount = Math.min(amount, this.size);
const iterable = this.values();
return Array.from({ length: amount }, (): V => iterable.next().value);
}
/**
* Returns the last element in the collection
*/
last(): V | undefined;
/**
* Returns an Array of the values from the correspondant `amount`
* @param amount The amount to fetch from
*/
last(amount: number): V[];
/**
* Returns the last element in the collection or an Array of the values from the correspondant `amount`
* @param amount The amount to fetch from
*/
last(amount?: number): V | V[] | undefined {
const iter = [...this.values()];
if (typeof amount === 'undefined') return iter[iter.length - 1];
if (amount < 0) return this.first(amount! * -1);
if (!amount) return [];
return iter.slice(-amount);
}
/**
* Returns the last element in the collection
*/
lastKey(): K | undefined;
/**
* Returns an Array of the values from the correspondant `amount`
* @param amount The amount to fetch from
*/
lastKey(amount: number): K[];
/**
* Returns the last element in the collection or an Array of the values from the correspondant `amount`
* @param amount The amount to fetch from
*/
lastKey(amount?: number): K | K[] | undefined {
const iter = [...this.keys()];
if (typeof amount === 'undefined') return iter[iter.length - 1];
if (amount < 0) return this.firstKey(amount! * -1);
if (!amount) return [];
return iter.slice(-amount);
}
/**
* Returns the first key in the collection
*/
firstKey(): K | undefined;
/**
* Returns an Array of the keys from the correspondant `amount`
* @param amount The amount to fetch from
*/
firstKey(amount: number): K[];
/**
* Returns the first key in the collection or an Array of the values from the correspondant `amount`
* @param amount The amount to fetch from
*/
firstKey(amount?: number): K | K[] | undefined {
if (typeof amount === 'undefined') {
return this.keys().next().value;
}
if (amount < 0) return this.lastKey(amount! * -1);
amount = Math.min(amount, this.size);
const iterable = this.keys();
return Array.from({ length: amount }, (): K => iterable.next().value);
}
/**
* Returns all of the values as an Array
*/
toArray() {
return [...this.values()];
}
/**
* Returns all of the keys as an Array
*/
toKeyArray() {
return [...this.keys()];
}
/**
* Gets the first item in the collection and removes it (if provided)
* @param remove If we should remove it or not
*/
shift(remove: boolean = false) {
const item = this.first();
const key = this.firstKey();
if (item === undefined || key === undefined) return null;
if (remove) this.delete(key);
return item;
}
/**
* Gets the last item in the collection and removes it(if provided)
* @param remove If we should remove it or not
*/
unshift(remove: boolean = false) {
const item = this.last();
const key = this.lastKey();
if (item === undefined || key === undefined) return null;
if (remove) this.delete(key);
return item;
}
/**
* Find a value in the collection from it's predicate function
* @param predicate The predicate function
* @param thisArg An additional `this` context if needed
* @returns The value found or `null` if not found
*/
find<ThisArg = Collection<K, V>>(predicate: Predicate<ThisArg, V, number, K, boolean>, thisArg?: ThisArg) {
let idx = -1;
let result: V | null = null;
for (const [key, value] of this.entries()) {
if (predicate.call(thisArg !== undefined ? thisArg : (this as any), value, ++idx, key)) {
result = value;
break;
}
}
return result;
}
/**
* Finds a key in the collection from it's predicate function
* @param predicate The predicate function
* @param thisArg An additional `this` context if needed
* @returns The key found or `null` if not found
*/
findKey<ThisArg = Collection<K, V>>(predicate: MinimalPredicate<ThisArg, V, boolean>, thisArg?: ThisArg) {
let func: UndetailedMinimalPredicate<V, boolean>;
if (thisArg !== undefined) func = predicate.bind(thisArg);
else func = predicate.bind(<any>this);
let result: K | null = null;
for (const [key, value] of this.entries()) {
if (func(value)) {
result = key;
break;
}
}
return result;
}
/**
* Computes a value if it's absent in this Collection
* @param key The key to find
* @param insert Item to add when it doesn't exist
*/
emplace(key: K, insert: V | (() => V)) {
if (!this.has(key)) {
const item = typeof insert === 'function' ? (insert as any)() : insert;
this.set(key, item);
return item as unknown as V;
} else {
return this.get(key)!;
}
}
/**
* Similar to [Array.sort], which basically sorts the values of this Collection
* to return a value
*
* @param compareFn The compare function
* @returns The value
*/
sort(compareFn: (a: V, b: V) => number) {
const values = this.toArray();
values.sort(compareFn);
return values;
}
/**
* Similar to [Array.sort], which basically sorts the values of this Collection
* to return a value
*
* @param compareFn The compare function
* @returns The value
*/
sortKeys(compareFn: (a: K, b: K) => number) {
const keys = this.toKeyArray();
keys.sort(compareFn);
return keys;
}
/**
* Similar to [Array.some], this function tests whether atleast 1 item
* in the predicate function passes the test in the values cache.
*
* @param func The function to use to filter out
* @returns A boolean value if 1 item of the cache is truthy
*/
some(func: (item: V) => boolean) {
const values = this.toArray();
for (let i = 0; i < values.length; i++) {
if (func.call(this, values[i])) return true;
}
return false;
}
/**
* Similar to [Array.some], this functions tests whether atleast 1 key
* in the predicate function passes the test in the key cache.
*
* @param func The function to use to filter out
* @returns A boolean value if 1 item of the cache is truthy
*/
someKeys(func: (item: K) => boolean) {
const keys = this.toKeyArray();
for (let i = 0; i < keys.length; i++) {
if (func.call(this, keys[i])) return true;
}
return false;
}
/**
* Deletes any entries that satisfy the predicate function.
* @param predicate The predicate function
* @param thisArg A custom `this` context provided value for [[predicate]].
* @returns The size from the previous size and the current size.
*/
sweep<ThisArg = Collection<K, V>>(predicate: Predicate<ThisArg, V, number, K, boolean>, thisArg?: ThisArg) {
const func = thisArg !== undefined ? predicate.bind(thisArg) : predicate;
const prevSize = this.size;
let idx = -1;
for (const [key, value] of this) {
if (func.call(thisArg !== undefined ? thisArg : (this as any), value, ++idx, key)) {
this.delete(key);
}
}
return prevSize - this.size;
}
/**
* Clears every element in this [[Collection]].
*/
clear() {
if (this._sweepInterval !== undefined) clearInterval(this._sweepInterval);
super.clear();
}
}