/ components / CustomSelect / option-map.ts
option-map.ts
 1  import type { ReactNode } from 'react'
 2  import type { OptionWithDescription } from './select.js'
 3  
 4  type OptionMapItem<T> = {
 5    label: ReactNode
 6    value: T
 7    description?: string
 8    previous: OptionMapItem<T> | undefined
 9    next: OptionMapItem<T> | undefined
10    index: number
11  }
12  
13  export default class OptionMap<T> extends Map<T, OptionMapItem<T>> {
14    readonly first: OptionMapItem<T> | undefined
15    readonly last: OptionMapItem<T> | undefined
16  
17    constructor(options: OptionWithDescription<T>[]) {
18      const items: Array<[T, OptionMapItem<T>]> = []
19      let firstItem: OptionMapItem<T> | undefined
20      let lastItem: OptionMapItem<T> | undefined
21      let previous: OptionMapItem<T> | undefined
22      let index = 0
23  
24      for (const option of options) {
25        const item = {
26          label: option.label,
27          value: option.value,
28          description: option.description,
29          previous,
30          next: undefined,
31          index,
32        }
33  
34        if (previous) {
35          previous.next = item
36        }
37  
38        firstItem ||= item
39        lastItem = item
40  
41        items.push([option.value, item])
42        index++
43        previous = item
44      }
45  
46      super(items)
47      this.first = firstItem
48      this.last = lastItem
49    }
50  }