1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 const DEFAULT_CIRCULAR_ARRAY_SIZE
= 1024
6 * Array with a maximum length and shifting items when full.
8 export class CircularArray
<T
> extends Array<T
> {
11 constructor (size
: number = DEFAULT_CIRCULAR_ARRAY_SIZE
, ...items
: T
[]) {
15 if (arguments.length
> 1) {
21 public push (...items
: T
[]): number {
22 const length
= super.push(...items
)
23 if (length
> this.size
) {
24 super.splice(0, length
- this.size
)
30 public unshift (...items
: T
[]): number {
31 const length
= super.unshift(...items
)
32 if (length
> this.size
) {
33 super.splice(this.size
, items
.length
)
39 public concat (...items
: Array<T
| ConcatArray
<T
>>): CircularArray
<T
> {
40 const concatenatedCircularArray
= super.concat(
43 concatenatedCircularArray
.size
= this.size
44 if (concatenatedCircularArray
.length
> concatenatedCircularArray
.size
) {
45 concatenatedCircularArray
.splice(
47 concatenatedCircularArray
.length
- concatenatedCircularArray
.size
50 return concatenatedCircularArray
59 let itemsRemoved
: T
[] = []
60 if (arguments.length
>= 3 && deleteCount
!= null) {
61 itemsRemoved
= super.splice(start
, deleteCount
, ...items
)
62 if (this.length
> this.size
) {
63 const itemsOverflowing
= super.splice(0, this.length
- this.size
)
64 itemsRemoved
= new CircularArray
<T
>(
65 itemsRemoved
.length
+ itemsOverflowing
.length
,
70 } else if (arguments.length
=== 2) {
71 itemsRemoved
= super.splice(start
, deleteCount
)
73 itemsRemoved
= super.splice(start
)
75 return itemsRemoved
as CircularArray
<T
>
78 public resize (size
: number): void {
82 } else if (size
< this.size
) {
83 for (let i
= size
; i
< this.size
; i
++) {
90 public empty (): boolean {
91 return this.length
=== 0
94 public full (): boolean {
95 return this.length
=== this.size
98 private checkSize (size
: number): void {
99 if (!Number.isSafeInteger(size
)) {
101 `Invalid circular array size: ${size} is not a safe integer`
105 throw new RangeError(`Invalid circular array size: ${size} < 0`)