1 // Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 export const DEFAULT_CIRCULAR_ARRAY_SIZE
= 1024
6 * Array with a maximum length and shifting items when full.
10 export class CircularArray
<T
> extends Array<T
> {
13 constructor (size
: number = DEFAULT_CIRCULAR_ARRAY_SIZE
, ...items
: T
[]) {
17 if (arguments.length
> 1) {
23 public push (...items
: T
[]): number {
24 const length
= super.push(...items
)
25 if (length
> this.size
) {
26 super.splice(0, length
- this.size
)
32 public unshift (...items
: T
[]): number {
33 const length
= super.unshift(...items
)
34 if (length
> this.size
) {
35 super.splice(this.size
, items
.length
)
41 public concat (...items
: Array<T
| ConcatArray
<T
>>): CircularArray
<T
> {
42 const concatenatedCircularArray
= super.concat(
45 concatenatedCircularArray
.size
= this.size
46 if (concatenatedCircularArray
.length
> concatenatedCircularArray
.size
) {
47 concatenatedCircularArray
.splice(
49 concatenatedCircularArray
.length
- concatenatedCircularArray
.size
52 return concatenatedCircularArray
61 let itemsRemoved
: T
[] = []
62 if (arguments.length
>= 3 && deleteCount
!= null) {
63 itemsRemoved
= super.splice(start
, deleteCount
, ...items
)
64 if (this.length
> this.size
) {
65 const itemsOverflowing
= super.splice(0, this.length
- this.size
)
66 itemsRemoved
= new CircularArray
<T
>(
67 itemsRemoved
.length
+ itemsOverflowing
.length
,
72 } else if (arguments.length
=== 2) {
73 itemsRemoved
= super.splice(start
, deleteCount
)
75 itemsRemoved
= super.splice(start
)
77 return itemsRemoved
as CircularArray
<T
>
80 public resize (size
: number): void {
84 } else if (size
< this.size
) {
85 for (let i
= size
; i
< this.size
; i
++) {
92 public empty (): boolean {
93 return this.length
=== 0
96 public full (): boolean {
97 return this.length
=== this.size
100 private checkSize (size
: number): void {
101 if (!Number.isSafeInteger(size
)) {
103 `Invalid circular array size: ${size} is not a safe integer`
107 throw new RangeError(`Invalid circular array size: ${size} < 0`)