1 // Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
3 export const DEFAULT_CIRCULAR_ARRAY_SIZE
= 385
6 * Array with a maximum length and shifting items when full.
8 * @typeParam T - Type of items.
11 export class CircularArray
<T
> extends Array<T
> {
14 constructor (size
: number = DEFAULT_CIRCULAR_ARRAY_SIZE
, ...items
: T
[]) {
18 if (arguments.length
> 1) {
24 public push (...items
: T
[]): number {
25 const length
= super.push(...items
)
26 if (length
> this.size
) {
27 super.splice(0, length
- this.size
)
33 public unshift (...items
: T
[]): number {
34 const length
= super.unshift(...items
)
35 if (length
> this.size
) {
36 super.splice(this.size
, items
.length
)
42 public concat (...items
: Array<T
| ConcatArray
<T
>>): CircularArray
<T
> {
43 const concatenatedCircularArray
= super.concat(
46 concatenatedCircularArray
.size
= this.size
47 if (concatenatedCircularArray
.length
> concatenatedCircularArray
.size
) {
48 concatenatedCircularArray
.splice(
50 concatenatedCircularArray
.length
- concatenatedCircularArray
.size
53 return concatenatedCircularArray
62 let itemsRemoved
: T
[] = []
63 if (arguments.length
>= 3 && deleteCount
!= null) {
64 itemsRemoved
= super.splice(start
, deleteCount
, ...items
)
65 if (this.length
> this.size
) {
66 const itemsOverflowing
= super.splice(0, this.length
- this.size
)
67 itemsRemoved
= new CircularArray
<T
>(
68 itemsRemoved
.length
+ itemsOverflowing
.length
,
73 } else if (arguments.length
=== 2) {
74 itemsRemoved
= super.splice(start
, deleteCount
)
76 itemsRemoved
= super.splice(start
)
78 return itemsRemoved
as CircularArray
<T
>
81 public resize (size
: number): void {
85 } else if (size
< this.size
) {
86 for (let i
= size
; i
< this.size
; i
++) {
93 public empty (): boolean {
94 return this.length
=== 0
97 public full (): boolean {
98 return this.length
=== this.size
101 private checkSize (size
: number): void {
102 if (!Number.isSafeInteger(size
)) {
104 `Invalid circular array size: ${size} is not a safe integer`
108 throw new RangeError(`Invalid circular array size: ${size} < 0`)