From d43a619b43edfc37cd16020f42adb3893f002d9a Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Thu, 13 May 2021 19:39:36 +0200 Subject: [PATCH] Add some methods to the circular array. MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/utils/CircularArray.ts | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) 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; + } } -- 2.34.1