From: Jérôme Benoit Date: Thu, 13 May 2021 17:39:36 +0000 (+0200) Subject: Add some methods to the circular array. X-Git-Tag: v1.0.1-0~17 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=d43a619b43edfc37cd16020f42adb3893f002d9a;p=e-mobility-charging-stations-simulator.git Add some methods to the circular array. Signed-off-by: Jérôme Benoit --- diff --git a/src/utils/CircularArray.ts b/src/utils/CircularArray.ts index ba3eba19..9fde8be7 100644 --- a/src/utils/CircularArray.ts +++ b/src/utils/CircularArray.ts @@ -1,36 +1,58 @@ export default class CircularArray extends Array { public size: number; - private readonly maximumCircularArraySize = 2000; + private readonly defaultMaximumCircularArraySize = 2000; constructor(size?: number) { super(); - this.size = size && size <= this.maximumCircularArraySize ? size : this.maximumCircularArraySize; + this.size = size && size <= this.defaultMaximumCircularArraySize ? size : this.defaultMaximumCircularArraySize; } - push(...items: T[]): number { + public push(...items: T[]): number { if (this.length + items.length > this.size) { super.splice(0, (this.length + items.length) - this.size); } return super.push(...items); } - unshift(...items: T[]): number { + public unshift(...items: T[]): number { if (this.length + items.length > this.size) { super.splice(this.size - items.length, (this.length + items.length) - this.size); } return super.unshift(...items); } - concat(...items: (T | ConcatArray)[]): T[] { + public concat(...items: (T | ConcatArray)[]): T[] { if (this.length + items.length > this.size) { super.splice(0, (this.length + items.length) - this.size); } return super.concat(items as T[]); } - splice(start: number, deleteCount?: number, ...items: T[]): T[] { + public splice(start: number, deleteCount?: number, ...items: T[]): T[] { this.push(...items); return super.splice(start, deleteCount); } + + public resize(size: number): void { + if (size < 0) { + throw new RangeError( + 'circular array size does not allow negative values.' + ); + } + if (size === 0) { + this.length = 0; + } else if (size !== this.size) { + this.slice(-size); + } + this.size = size; + } + + public empty(): boolean { + return this.length === 0; + } + + public full(): boolean { + return this.length === this.size; + } }