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
|
'use strict';
const { Collection } = require('@discordjs/collection');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Options for defining the behavior of a LimitedCollection
* @typedef {Object} LimitedCollectionOptions
* @property {?number} [maxSize=Infinity] The maximum size of the Collection
* @property {?Function} [keepOverLimit=null] A function, which is passed the value and key of an entry, ran to decide
* to keep an entry past the maximum size
*/
/**
* A Collection which holds a max amount of entries.
* @extends {Collection}
* @param {LimitedCollectionOptions} [options={}] Options for constructing the Collection.
* @param {Iterable} [iterable=null] Optional entries passed to the Map constructor.
*/
class LimitedCollection extends Collection {
constructor(options = {}, iterable) {
if (typeof options !== 'object' || options === null) {
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
}
const { maxSize = Infinity, keepOverLimit = null } = options;
if (typeof maxSize !== 'number') {
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'maxSize', 'number');
}
if (keepOverLimit !== null && typeof keepOverLimit !== 'function') {
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'keepOverLimit', 'function');
}
super(iterable);
/**
* The max size of the Collection.
* @type {number}
*/
this.maxSize = maxSize;
/**
* A function called to check if an entry should be kept when the Collection is at max size.
* @type {?Function}
*/
this.keepOverLimit = keepOverLimit;
}
set(key, value) {
if (this.maxSize === 0 && !this.keepOverLimit?.(value, key, this)) return this;
if (this.size >= this.maxSize && !this.has(key)) {
for (const [k, v] of this.entries()) {
const keep = this.keepOverLimit?.(v, k, this) ?? false;
if (!keep) {
this.delete(k);
break;
}
}
}
return super.set(key, value);
}
static get [Symbol.species]() {
return Collection;
}
}
module.exports = LimitedCollection;
|