1
+ /**
2
+ * Options for configuring an ItemBelt instance.
3
+ */
4
+ export type ItemBeltOptions = {
5
+ /**
6
+ * The initial index to set for the ItemBelt.
7
+ * If not provided, defaults to 0.
8
+ */
9
+ index ?: number ;
10
+ } ;
11
+
1
12
/**
2
13
* A class representing an item belt, which provides functionality for managing
3
14
* and selecting items in a list with wrap-around and bounded selection.
4
15
*
5
16
* @template T The type of items contained in the belt.
6
17
*/
7
18
export class ItemBelt < T > {
8
- #index = 0 ;
19
+ #index: number = 0 ;
9
20
#items: readonly T [ ] ;
10
21
11
22
/**
12
23
* Creates an instance of ItemBelt with the specified items.
13
24
*
14
25
* @param items An array of items of type T to initialize the belt.
26
+ * @param options Optional configuration for the ItemBelt.
27
+ * @param options.index The initial index to set (default is 0).
15
28
*/
16
- constructor ( items : readonly T [ ] ) {
29
+ constructor ( items : readonly T [ ] , options ?: ItemBeltOptions ) {
17
30
this . #items = items ;
31
+ this . index = options ?. index ?? 0 ;
18
32
}
19
33
20
34
/**
@@ -73,7 +87,9 @@ export class ItemBelt<T> {
73
87
* to the nearest valid value.
74
88
*/
75
89
set index ( index : number ) {
76
- if ( index >= this . #items. length ) {
90
+ if ( this . #items. length === 0 ) {
91
+ index = 0 ;
92
+ } else if ( index >= this . #items. length ) {
77
93
index = this . #items. length - 1 ;
78
94
} else if ( index < 0 ) {
79
95
index = 0 ;
@@ -85,8 +101,8 @@ export class ItemBelt<T> {
85
101
* Selects a new item based on the current index, with an optional offset.
86
102
* The selection can optionally cycle through the items list.
87
103
*
104
+ * @param offset The number of positions to move the index (default is 1).
88
105
* @param options Optional configuration for the selection.
89
- * @param options.offset The number of positions to move the index (default is 1).
90
106
* @param options.cycle Whether to cycle through the list (default is `false`).
91
107
*/
92
108
select ( offset = 1 , { cycle = false } = { } ) : void {
0 commit comments