utils/ts-src/limitedArray.ts

68 lines
1.3 KiB
TypeScript

export class limitedArray {
_array: unknown[];
_limit: number;
/**
* Used to construct the LimitedArray
* Defaults to 100 when no size is passed in
* @param size
*/
constructor(size = 100) {
this._array = [];
this._limit = size;
}
/**
* Add items to the end of an array
* @param item
*/
push(item: unknown): void {
this._array.push(item);
if (this._array.length > this._limit) this._array.shift();
}
/**
* Return the items within the array
* @returns {[]}
*/
get(): unknown[] {
return this._array;
}
/**
* Limits the size of the array
* @param size
*/
limit(size: number): void {
this._limit = size;
if (this._array.length > this._limit) this._array = this._array.slice(this._array.length - this._limit);
}
/**
* Returns the length of the array
* @returns {number}
*/
length(): number {
return this._array.length;
}
/**
* Bulk add an array to the array
* @param items
*/
add(items: unknown[]): void {
this._array = this._array.concat(items);
if (this._array.length > this._limit) this._array = this._array.slice(this._array.length - this._limit);
}
/**
* Remove an item from the beginning of an array
* @returns {*}
*/
shift(): unknown {
return this._array.shift();
}
}