Allow unbound circular array size
[e-mobility-charging-stations-simulator.git] / src / utils / CircularArray.ts
CommitLineData
edfb206c
JB
1
2export default class CircularArray<T> extends Array<T> {
365f6bc9 3 public size: number;
2541c612 4 private readonly defaultCircularArraySize = 2000;
edfb206c 5
53f53d65 6 constructor(size?: number) {
edfb206c 7 super();
2541c612 8 this.size = size ?? this.defaultCircularArraySize;
edfb206c
JB
9 }
10
d43a619b 11 public push(...items: T[]): number {
b6633b4c
JB
12 if (this.length + items.length > this.size) {
13 super.splice(0, (this.length + items.length) - this.size);
edfb206c
JB
14 }
15 return super.push(...items);
16 }
17
d43a619b 18 public unshift(...items: T[]): number {
b6633b4c
JB
19 if (this.length + items.length > this.size) {
20 super.splice(this.size - items.length, (this.length + items.length) - this.size);
edfb206c
JB
21 }
22 return super.unshift(...items);
23 }
c70ff58d 24
d43a619b 25 public concat(...items: (T | ConcatArray<T>)[]): T[] {
c70ff58d
JB
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
d43a619b 32 public splice(start: number, deleteCount?: number, ...items: T[]): T[] {
c70ff58d
JB
33 this.push(...items);
34 return super.splice(start, deleteCount);
35 }
d43a619b
JB
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 }
edfb206c 58}