Allow unbound circular array size
[e-mobility-charging-stations-simulator.git] / src / utils / CircularArray.ts
1
2 export default class CircularArray<T> extends Array<T> {
3 public size: number;
4 private readonly defaultCircularArraySize = 2000;
5
6 constructor(size?: number) {
7 super();
8 this.size = size ?? this.defaultCircularArraySize;
9 }
10
11 public push(...items: T[]): number {
12 if (this.length + items.length > this.size) {
13 super.splice(0, (this.length + items.length) - this.size);
14 }
15 return super.push(...items);
16 }
17
18 public unshift(...items: T[]): number {
19 if (this.length + items.length > this.size) {
20 super.splice(this.size - items.length, (this.length + items.length) - this.size);
21 }
22 return super.unshift(...items);
23 }
24
25 public concat(...items: (T | ConcatArray<T>)[]): T[] {
26 if (this.length + items.length > this.size) {
27 super.splice(0, (this.length + items.length) - this.size);
28 }
29 return super.concat(items as T[]);
30 }
31
32 public splice(start: number, deleteCount?: number, ...items: T[]): T[] {
33 this.push(...items);
34 return super.splice(start, deleteCount);
35 }
36
37 public resize(size: number): void {
38 if (size < 0) {
39 throw new RangeError(
40 'circular array size does not allow negative values.'
41 );
42 }
43 if (size === 0) {
44 this.length = 0;
45 } else if (size !== this.size) {
46 this.slice(-size);
47 }
48 this.size = size;
49 }
50
51 public empty(): boolean {
52 return this.length === 0;
53 }
54
55 public full(): boolean {
56 return this.length === this.size;
57 }
58 }