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+
112/**
213 * A class representing an item belt, which provides functionality for managing
314 * and selecting items in a list with wrap-around and bounded selection.
415 *
516 * @template T The type of items contained in the belt.
617 */
718export class ItemBelt < T > {
8- #index = 0 ;
19+ #index: number = 0 ;
920 #items: readonly T [ ] ;
1021
1122 /**
1223 * Creates an instance of ItemBelt with the specified items.
1324 *
1425 * @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).
1528 */
16- constructor ( items : readonly T [ ] ) {
29+ constructor ( items : readonly T [ ] , options ?: ItemBeltOptions ) {
1730 this . #items = items ;
31+ this . index = options ?. index ?? 0 ;
1832 }
1933
2034 /**
@@ -73,7 +87,9 @@ export class ItemBelt<T> {
7387 * to the nearest valid value.
7488 */
7589 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 ) {
7793 index = this . #items. length - 1 ;
7894 } else if ( index < 0 ) {
7995 index = 0 ;
@@ -85,8 +101,8 @@ export class ItemBelt<T> {
85101 * Selects a new item based on the current index, with an optional offset.
86102 * The selection can optionally cycle through the items list.
87103 *
104+ * @param offset The number of positions to move the index (default is 1).
88105 * @param options Optional configuration for the selection.
89- * @param options.offset The number of positions to move the index (default is 1).
90106 * @param options.cycle Whether to cycle through the list (default is `false`).
91107 */
92108 select ( offset = 1 , { cycle = false } = { } ) : void {
0 commit comments