Fix circular array initialization
[e-mobility-charging-stations-simulator.git] / src / utils / CircularArray.ts
CommitLineData
1699e597 1const DEFAULT_CIRCULAR_ARRAY_SIZE = 2000;
edfb206c
JB
2
3export default class CircularArray<T> extends Array<T> {
365f6bc9 4 public size: number;
edfb206c 5
534434b0 6 constructor(size: number = DEFAULT_CIRCULAR_ARRAY_SIZE, ...items: T[]) {
edfb206c 7 super();
534434b0
JB
8 this.checkSize(size);
9 this.size = size;
10 if (arguments.length > 1) {
11 this.push(...items);
12 }
edfb206c
JB
13 }
14
d43a619b 15 public push(...items: T[]): number {
534434b0
JB
16 const length = super.push(...items);
17 if (length > this.size) {
18 super.splice(0, length - this.size);
edfb206c 19 }
534434b0 20 return this.length;
edfb206c
JB
21 }
22
d43a619b 23 public unshift(...items: T[]): number {
534434b0
JB
24 const length = super.unshift(...items);
25 if (length > this.size) {
26 super.splice(this.size, items.length);
edfb206c 27 }
534434b0 28 return length;
edfb206c 29 }
c70ff58d 30
534434b0
JB
31 public concat(...items: (T | ConcatArray<T>)[]): CircularArray<T> {
32 const concatenatedCircularArray = super.concat(
33 items as T[]
34 ) as CircularArray<T>;
35 concatenatedCircularArray.size = this.size;
36 if (concatenatedCircularArray.length > concatenatedCircularArray.size) {
37 concatenatedCircularArray.splice(
38 0,
39 concatenatedCircularArray.length - this.size
40 );
c70ff58d 41 }
534434b0 42 return concatenatedCircularArray;
c70ff58d
JB
43 }
44
d43a619b 45 public splice(start: number, deleteCount?: number, ...items: T[]): T[] {
534434b0
JB
46 let itemsRemoved: T[];
47 if (arguments.length >= 3 && typeof deleteCount !== 'undefined') {
48 itemsRemoved = super.splice(start, deleteCount);
49 // FIXME: that makes the items insert not in place
50 this.push(...items);
51 } else if (arguments.length === 2) {
52 itemsRemoved = super.splice(start, deleteCount);
53 } else {
54 itemsRemoved = super.splice(start);
55 }
56 return itemsRemoved;
c70ff58d 57 }
d43a619b
JB
58
59 public resize(size: number): void {
534434b0 60 this.checkSize(size);
d43a619b
JB
61 if (size === 0) {
62 this.length = 0;
534434b0
JB
63 } else if (size < this.size) {
64 for (let i = size; i < this.size; i++) {
65 super.pop();
66 }
d43a619b
JB
67 }
68 this.size = size;
69 }
70
71 public empty(): boolean {
72 return this.length === 0;
73 }
74
75 public full(): boolean {
76 return this.length === this.size;
77 }
534434b0
JB
78
79 private checkSize(size: number) {
80 if (size < 0) {
81 throw new RangeError('Invalid circular array size');
82 }
83 }
edfb206c 84}