-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
collection.ts
842 lines (774 loc) · 29.8 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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
/* eslint-disable no-param-reassign */
/**
* @internal
*/
export interface CollectionConstructor {
new (): Collection<unknown, unknown>;
new <K, V>(entries?: readonly (readonly [K, V])[] | null): Collection<K, V>;
new <K, V>(iterable: Iterable<readonly [K, V]>): Collection<K, V>;
readonly prototype: Collection<unknown, unknown>;
readonly [Symbol.species]: CollectionConstructor;
}
/**
* Represents an immutable version of a collection
*/
export type ReadonlyCollection<K, V> = Omit<
Collection<K, V>,
'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'
> &
ReadonlyMap<K, V>;
/**
* Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself
*
* @internal
*/
export interface Collection<K, V> extends Map<K, V> {
constructor: CollectionConstructor;
}
/**
* A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has
* an ID, for significantly improved performance and ease-of-use.
*
* @typeParam K - The key type this collection holds
* @typeParam V - The value type this collection holds
*/
export class Collection<K, V> extends Map<K, V> {
/**
* Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.
*
* @param key - The key to get if it exists, or set otherwise
* @param defaultValueGenerator - A function that generates the default value
* @example
* ```ts
* collection.ensure(guildId, () => defaultGuildConfig);
* ```
*/
public ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {
if (this.has(key)) return this.get(key)!;
if (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);
const defaultValue = defaultValueGenerator(key, this);
this.set(key, defaultValue);
return defaultValue;
}
/**
* Checks if all of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if all of the elements exist, `false` if at least one does not exist.
*/
public hasAll(...keys: K[]) {
return keys.every((key) => super.has(key));
}
/**
* Checks if any of the elements exist in the collection.
*
* @param keys - The keys of the elements to check for
* @returns `true` if any of the elements exist, `false` if none exist.
*/
public hasAny(...keys: K[]) {
return keys.some((key) => super.has(key));
}
/**
* Obtains the first value(s) in this collection.
*
* @param amount - Amount of values to obtain from the beginning
* @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative
*/
public first(): V | undefined;
public first(amount: number): V[];
public first(amount?: number): V | V[] | undefined {
if (amount === undefined) return this.values().next().value;
if (amount < 0) return this.last(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.values();
return Array.from({ length: amount }, (): V => iter.next().value);
}
/**
* Obtains the first key(s) in this collection.
*
* @param amount - Amount of keys to obtain from the beginning
* @returns A single key if no amount is provided or an array of keys, starting from the end if
* amount is negative
*/
public firstKey(): K | undefined;
public firstKey(amount: number): K[];
public firstKey(amount?: number): K | K[] | undefined {
if (amount === undefined) return this.keys().next().value;
if (amount < 0) return this.lastKey(amount * -1);
amount = Math.min(this.size, amount);
const iter = this.keys();
return Array.from({ length: amount }, (): K => iter.next().value);
}
/**
* Obtains the last value(s) in this collection.
*
* @param amount - Amount of values to obtain from the end
* @returns A single value if no amount is provided or an array of values, starting from the start if
* amount is negative
*/
public last(): V | undefined;
public last(amount: number): V[];
public last(amount?: number): V | V[] | undefined {
const arr = [...this.values()];
if (amount === undefined) return arr[arr.length - 1];
if (amount < 0) return this.first(amount * -1);
if (!amount) return [];
return arr.slice(-amount);
}
/**
* Obtains the last key(s) in this collection.
*
* @param amount - Amount of keys to obtain from the end
* @returns A single key if no amount is provided or an array of keys, starting from the start if
* amount is negative
*/
public lastKey(): K | undefined;
public lastKey(amount: number): K[];
public lastKey(amount?: number): K | K[] | undefined {
const arr = [...this.keys()];
if (amount === undefined) return arr[arr.length - 1];
if (amount < 0) return this.firstKey(amount * -1);
if (!amount) return [];
return arr.slice(-amount);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the item at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the element to obtain
*/
public at(index: number) {
index = Math.floor(index);
const arr = [...this.values()];
return arr.at(index);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.
* Returns the key at a given index, allowing for positive and negative integers.
* Negative integers count back from the last item in the collection.
*
* @param index - The index of the key to obtain
*/
public keyAt(index: number) {
index = Math.floor(index);
const arr = [...this.keys()];
return arr.at(index);
}
/**
* Obtains unique random value(s) from this collection.
*
* @param amount - Amount of values to obtain randomly
* @returns A single value if no amount is provided or an array of values
*/
public random(): V | undefined;
public random(amount: number): V[];
public random(amount?: number): V | V[] | undefined {
const arr = [...this.values()];
if (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount) return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,
);
}
/**
* Obtains unique random key(s) from this collection.
*
* @param amount - Amount of keys to obtain randomly
* @returns A single key if no amount is provided or an array
*/
public randomKey(): K | undefined;
public randomKey(amount: number): K[];
public randomKey(amount?: number): K | K[] | undefined {
const arr = [...this.keys()];
if (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];
if (!arr.length || !amount) return [];
return Array.from(
{ length: Math.min(amount, arr.length) },
(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,
);
}
/**
* Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}
* but returns a Collection instead of an Array.
*/
public reverse() {
const entries = [...this.entries()].reverse();
this.clear();
for (const [key, value] of entries) this.set(key, value);
return this;
}
/**
* Searches for a single item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.
* All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you
* should use the `get` method. See
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.
*
* @param fn - The function to test with (should return boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.find(user => user.username === 'Bob');
* ```
*/
public find<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;
public find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;
public find<This, V2 extends V>(
fn: (this: This, value: V, key: K, collection: this) => value is V2,
thisArg: This,
): V2 | undefined;
public find<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;
public find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this)) return val;
}
return undefined;
}
/**
* Searches for the key of a single item where the given function returns a truthy value. This behaves like
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},
* but returns the key rather than the positional index.
*
* @param fn - The function to test with (should return boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.findKey(user => user.username === 'Bob');
* ```
*/
public findKey<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;
public findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;
public findKey<This, K2 extends K>(
fn: (this: This, value: V, key: K, collection: this) => key is K2,
thisArg: This,
): K2 | undefined;
public findKey<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;
public findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this)) return key;
}
return undefined;
}
/**
* Removes items that satisfy the provided filter function.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing function
* @returns The number of removed entries
*/
public sweep(fn: (value: V, key: K, collection: this) => unknown): number;
public sweep<T>(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;
public sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const previousSize = this.size;
for (const [key, val] of this) {
if (fn(val, key, this)) this.delete(key);
}
return previousSize - this.size;
}
/**
* Identical to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},
* but returns a Collection instead of an Array.
*
* @param fn - The function to test with (should return boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.filter(user => user.username === 'Bob');
* ```
*/
public filter<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): Collection<K2, V>;
public filter<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): Collection<K, V2>;
public filter(fn: (value: V, key: K, collection: this) => unknown): Collection<K, V>;
public filter<This, K2 extends K>(
fn: (this: This, value: V, key: K, collection: this) => key is K2,
thisArg: This,
): Collection<K2, V>;
public filter<This, V2 extends V>(
fn: (this: This, value: V, key: K, collection: this) => value is V2,
thisArg: This,
): Collection<K, V2>;
public filter<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection<K, V>;
public filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection<K, V> {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const results = new this.constructor[Symbol.species]<K, V>();
for (const [key, val] of this) {
if (fn(val, key, this)) results.set(key, val);
}
return results;
}
/**
* Partitions the collection into two collections where the first collection
* contains the items that passed and the second contains the items that failed.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* const [big, small] = collection.partition(guild => guild.memberCount > 250);
* ```
*/
public partition<K2 extends K>(
fn: (value: V, key: K, collection: this) => key is K2,
): [Collection<K2, V>, Collection<Exclude<K, K2>, V>];
public partition<V2 extends V>(
fn: (value: V, key: K, collection: this) => value is V2,
): [Collection<K, V2>, Collection<K, Exclude<V, V2>>];
public partition(fn: (value: V, key: K, collection: this) => unknown): [Collection<K, V>, Collection<K, V>];
public partition<This, K2 extends K>(
fn: (this: This, value: V, key: K, collection: this) => key is K2,
thisArg: This,
): [Collection<K2, V>, Collection<Exclude<K, K2>, V>];
public partition<This, V2 extends V>(
fn: (this: This, value: V, key: K, collection: this) => value is V2,
thisArg: This,
): [Collection<K, V2>, Collection<K, Exclude<V, V2>>];
public partition<This>(
fn: (this: This, value: V, key: K, collection: this) => unknown,
thisArg: This,
): [Collection<K, V>, Collection<K, V>];
public partition(
fn: (value: V, key: K, collection: this) => unknown,
thisArg?: unknown,
): [Collection<K, V>, Collection<K, V>] {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const results: [Collection<K, V>, Collection<K, V>] = [
new this.constructor[Symbol.species]<K, V>(),
new this.constructor[Symbol.species]<K, V>(),
];
for (const [key, val] of this) {
if (fn(val, key, this)) {
results[0].set(key, val);
} else {
results[1].set(key, val);
}
}
return results;
}
/**
* Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.
*
* @param fn - Function that produces a new Collection
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.flatMap(guild => guild.members.cache);
* ```
*/
public flatMap<T>(fn: (value: V, key: K, collection: this) => Collection<K, T>): Collection<K, T>;
public flatMap<T, This>(
fn: (this: This, value: V, key: K, collection: this) => Collection<K, T>,
thisArg: This,
): Collection<K, T>;
public flatMap<T>(fn: (value: V, key: K, collection: this) => Collection<K, T>, thisArg?: unknown): Collection<K, T> {
// eslint-disable-next-line unicorn/no-array-method-this-argument
const collections = this.map(fn, thisArg);
return new this.constructor[Symbol.species]<K, T>().concat(...collections);
}
/**
* Maps each item to another value into an array. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.
*
* @param fn - Function that produces an element of the new array, taking three arguments
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.map(user => user.tag);
* ```
*/
public map<T>(fn: (value: V, key: K, collection: this) => T): T[];
public map<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];
public map<T>(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const iter = this.entries();
return Array.from({ length: this.size }, (): T => {
const [key, value] = iter.next().value;
return fn(value, key, this);
});
}
/**
* Maps each item to another value into a collection. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.
*
* @param fn - Function that produces an element of the new collection, taking three arguments
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.mapValues(user => user.tag);
* ```
*/
public mapValues<T>(fn: (value: V, key: K, collection: this) => T): Collection<K, T>;
public mapValues<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection<K, T>;
public mapValues<T>(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection<K, T> {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
const coll = new this.constructor[Symbol.species]<K, T>();
for (const [key, val] of this) coll.set(key, fn(val, key, this));
return coll;
}
/**
* Checks if there exists an item that passes a test. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.some(user => user.discriminator === '0000');
* ```
*/
public some(fn: (value: V, key: K, collection: this) => unknown): boolean;
public some<T>(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;
public some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (fn(val, key, this)) return true;
}
return false;
}
/**
* Checks if all items passes a test. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.
*
* @param fn - Function used to test (should return a boolean)
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection.every(user => !user.bot);
* ```
*/
public every<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): this is Collection<K2, V>;
public every<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): this is Collection<K, V2>;
public every(fn: (value: V, key: K, collection: this) => unknown): boolean;
public every<This, K2 extends K>(
fn: (this: This, value: V, key: K, collection: this) => key is K2,
thisArg: This,
): this is Collection<K2, V>;
public every<This, V2 extends V>(
fn: (this: This, value: V, key: K, collection: this) => value is V2,
thisArg: This,
): this is Collection<K, V2>;
public every<This>(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;
public every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, val] of this) {
if (!fn(val, key, this)) return false;
}
return true;
}
/**
* Applies a function to produce a single value. Identical in behavior to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.
*
* @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,
* and `collection`
* @param initialValue - Starting value for the accumulator
* @example
* ```ts
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
public reduce<T>(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
let accumulator!: T;
if (initialValue !== undefined) {
accumulator = initialValue;
for (const [key, val] of this) accumulator = fn(accumulator, val, key, this);
return accumulator;
}
let first = true;
for (const [key, val] of this) {
if (first) {
accumulator = val as unknown as T;
first = false;
continue;
}
accumulator = fn(accumulator, val, key, this);
}
// No items iterated.
if (first) {
throw new TypeError('Reduce of empty collection with no initial value');
}
return accumulator;
}
/**
* Identical to
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},
* but returns the collection instead of undefined.
*
* @param fn - Function to execute for each element
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection
* .each(user => console.log(user.username))
* .filter(user => user.bot)
* .each(user => console.log(user.username));
* ```
*/
public each(fn: (value: V, key: K, collection: this) => void): this;
public each<T>(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;
public each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
for (const [key, value] of this) {
fn(value, key, this);
}
return this;
}
/**
* Runs a function on the collection and returns the collection.
*
* @param fn - Function to execute
* @param thisArg - Value to use as `this` when executing function
* @example
* ```ts
* collection
* .tap(coll => console.log(coll.size))
* .filter(user => user.bot)
* .tap(coll => console.log(coll.size))
* ```
*/
public tap(fn: (collection: this) => void): this;
public tap<T>(fn: (this: T, collection: this) => void, thisArg: T): this;
public tap(fn: (collection: this) => void, thisArg?: unknown): this {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
if (thisArg !== undefined) fn = fn.bind(thisArg);
fn(this);
return this;
}
/**
* Creates an identical shallow copy of this collection.
*
* @example
* ```ts
* const newColl = someColl.clone();
* ```
*/
public clone(): Collection<K, V> {
return new this.constructor[Symbol.species](this);
}
/**
* Combines this collection with others into a new collection. None of the source collections are modified.
*
* @param collections - Collections to merge
* @example
* ```ts
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ```
*/
public concat(...collections: ReadonlyCollection<K, V>[]) {
const newColl = this.clone();
for (const coll of collections) {
for (const [key, val] of coll) newColl.set(key, val);
}
return newColl;
}
/**
* Checks if this collection shares identical items with another.
* This is different to checking for equality using equal-signs, because
* the collections may be different objects, but contain the same data.
*
* @param collection - Collection to compare with
* @returns Whether the collections have identical contents
*/
public equals(collection: ReadonlyCollection<K, V>) {
if (!collection) return false; // runtime check
if (this === collection) return true;
if (this.size !== collection.size) return false;
for (const [key, value] of this) {
if (!collection.has(key) || value !== collection.get(key)) {
return false;
}
}
return true;
}
/**
* The sort method sorts the items of a collection in place and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.
* @example
* ```ts
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
public sort(compareFunction: Comparator<K, V> = Collection.defaultSort) {
const entries = [...this.entries()];
entries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));
// Perform clean-up
super.clear();
// Set the new entries
for (const [key, value] of entries) {
super.set(key, value);
}
return this;
}
/**
* The intersect method returns a new structure containing items where the keys and values are present in both original structures.
*
* @param other - The other Collection to filter against
*/
public intersect<T>(other: ReadonlyCollection<K, T>): Collection<K, T> {
const coll = new this.constructor[Symbol.species]<K, T>();
for (const [key, value] of other) {
if (this.has(key) && Object.is(value, this.get(key))) {
coll.set(key, value);
}
}
return coll;
}
/**
* The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.
*
* @param other - The other Collection to filter against
*/
public subtract<T>(other: ReadonlyCollection<K, T>): Collection<K, V> {
const coll = new this.constructor[Symbol.species]<K, V>();
for (const [key, value] of this) {
if (!other.has(key) || !Object.is(value, other.get(key))) {
coll.set(key, value);
}
}
return coll;
}
/**
* The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.
*
* @param other - The other Collection to filter against
*/
public difference<T>(other: ReadonlyCollection<K, T>): Collection<K, T | V> {
const coll = new this.constructor[Symbol.species]<K, T | V>();
for (const [key, value] of other) {
if (!this.has(key)) coll.set(key, value);
}
for (const [key, value] of this) {
if (!other.has(key)) coll.set(key, value);
}
return coll;
}
/**
* Merges two Collections together into a new Collection.
*
* @param other - The other Collection to merge with
* @param whenInSelf - Function getting the result if the entry only exists in this Collection
* @param whenInOther - Function getting the result if the entry only exists in the other Collection
* @param whenInBoth - Function getting the result if the entry exists in both Collections
* @example
* ```ts
* // Sums up the entries in two collections.
* coll.merge(
* other,
* x => ({ keep: true, value: x }),
* y => ({ keep: true, value: y }),
* (x, y) => ({ keep: true, value: x + y }),
* );
* ```
* @example
* ```ts
* // Intersects two collections in a left-biased manner.
* coll.merge(
* other,
* x => ({ keep: false }),
* y => ({ keep: false }),
* (x, _) => ({ keep: true, value: x }),
* );
* ```
*/
public merge<T, R>(
other: ReadonlyCollection<K, T>,
whenInSelf: (value: V, key: K) => Keep<R>,
whenInOther: (valueOther: T, key: K) => Keep<R>,
whenInBoth: (value: V, valueOther: T, key: K) => Keep<R>,
): Collection<K, R> {
const coll = new this.constructor[Symbol.species]<K, R>();
const keys = new Set([...this.keys(), ...other.keys()]);
for (const key of keys) {
const hasInSelf = this.has(key);
const hasInOther = other.has(key);
if (hasInSelf && hasInOther) {
const result = whenInBoth(this.get(key)!, other.get(key)!, key);
if (result.keep) coll.set(key, result.value);
} else if (hasInSelf) {
const result = whenInSelf(this.get(key)!, key);
if (result.keep) coll.set(key, result.value);
} else if (hasInOther) {
const result = whenInOther(other.get(key)!, key);
if (result.keep) coll.set(key, result.value);
}
}
return coll;
}
/**
* The sorted method sorts the items of a collection and returns it.
* The sort is not necessarily stable in Node 10 or older.
* The default sort order is according to string Unicode code points.
*
* @param compareFunction - Specifies a function that defines the sort order.
* If omitted, the collection is sorted according to each character's Unicode code point value,
* according to the string conversion of each element.
* @example
* ```ts
* collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
public sorted(compareFunction: Comparator<K, V> = Collection.defaultSort) {
return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));
}
public toJSON() {
// toJSON is called recursively by JSON.stringify.
return [...this.values()];
}
private static defaultSort<V>(firstValue: V, secondValue: V): number {
return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;
}
/**
* Creates a Collection from a list of entries.
*
* @param entries - The list of entries
* @param combine - Function to combine an existing entry with a new one
* @example
* ```ts
* Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
* // returns Collection { "a" => 3, "b" => 2 }
* ```
*/
public static combineEntries<K, V>(
entries: Iterable<[K, V]>,
combine: (firstValue: V, secondValue: V, key: K) => V,
): Collection<K, V> {
const coll = new Collection<K, V>();
for (const [key, value] of entries) {
if (coll.has(key)) {
coll.set(key, combine(coll.get(key)!, value, key));
} else {
coll.set(key, value);
}
}
return coll;
}
}
/**
* @internal
*/
export type Keep<V> = { keep: false } | { keep: true; value: V };
/**
* @internal
*/
export type Comparator<K, V> = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;