CircularArray.ts: Fix unshift return
[e-mobility-charging-stations-simulator.git] / src / utils / CircularArray.ts
1 export const DEFAULT_CIRCULAR_ARRAY_SIZE = 2000;
2
3 export class CircularArray<T> extends Array<T> {
4 public size: number;
5
6 constructor(size: number = DEFAULT_CIRCULAR_ARRAY_SIZE, ...items: T[]) {
7 super();
8 this.checkSize(size);
9 this.size = size;
10 if (arguments.length > 1) {
11 this.push(...items);
12 }
13 }
14
15 public push(...items: T[]): number {
16 const length = super.push(...items);
17 if (length > this.size) {
18 super.splice(0, length - this.size);
19 }
20 return this.length;
21 }
22
23 public unshift(...items: T[]): number {
24 const length = super.unshift(...items);
25 if (length > this.size) {
26 super.splice(this.size, items.length);
27 }
28 return this.length;
29 }
30
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 - concatenatedCircularArray.size
40 );
41 }
42 return concatenatedCircularArray;
43 }
44
45 public splice(start: number, deleteCount?: number, ...items: T[]): T[] {
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;
57 }
58
59 public resize(size: number): void {
60 this.checkSize(size);
61 if (size === 0) {
62 this.length = 0;
63 } else if (size < this.size) {
64 for (let i = size; i < this.size; i++) {
65 super.pop();
66 }
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 }
78
79 private checkSize(size: number) {
80 if (size < 0) {
81 throw new RangeError('Invalid circular array size');
82 }
83 }
84 }