@creejs/commons-collection
Version:
Commons Collection
85 lines (84 loc) • 2.64 kB
TypeScript
/**
* A set that has a fixed capacity and automatically removes the oldest element when the capacity is reached.
*
* @class CappedSet
*/
export default class CappedSet {
/**
* Creates a new CappedSet instance with a fixed capacity.
* @constructor
* @param {number} capacity - The maximum number of elements the set can hold (must be > 0)
* @throws {Error} If capacity is less than or equal to 0
*/
constructor(capacity: number);
capacity: number;
/**
* 1. key is the Value stored in CappedSet
* 2. value is a Node
* 3. JS Map preserve the insertion order
* @type {Map<any, Node>}
*/
_map: Map<any, Node>;
/**
* @type {Node|undefined}
*/
_head: Node | undefined;
/**
* @type {Node|undefined}
*/
_tail: Node | undefined;
get size(): number;
/**
* get the oldest element
*/
get oldest(): any;
/**
* get the newest element
*/
get newest(): any;
/**
* Adds a value to the capped set. If the value already exists, it will be moved to the most recent position.
* If the set is at capacity, the oldest element will be removed before adding the new value.
* @param {*} value - The value to add to the set
*/
add(value: any): void;
/**
* Checks if the value exists in the set.
* @param {*} value - The value to check for existence.
* @returns {boolean} True if the value exists, false otherwise.
*/
has(value: any): boolean;
/**
* Deletes a value from the capped set.
* @param {*} value - The value to remove from the set.
* @returns {boolean} True if the value was found and removed, false otherwise.
*/
delete(value: any): boolean;
clear(): void;
/**
* Returns an iterator of the values in the set.
* @returns {Iterator<any>} An iterator object that yields the values of the set.
*/
values(): Iterator<any>;
/**
* Adds a new value to the set by creating a node and appending it to the tail.
* Updates the linked list structure and maintains the set's size.
* @private
* @param {*} value - The value to be added to the set.
*/
private _addNew;
/**
* Removes a node from the linked list and the internal Set.
* Updates head/tail pointers and maintains list consistency.
* @param {Node} node - The node to be removed
* @private
*/
private _removeNode;
_removeOldest(): void;
[Symbol.iterator](): MapIterator<any>;
}
export type Node = {
value: any;
prev: Node | undefined;
next: Node | undefined;
};