All files / src/hooks/slot slot.ts

100% Statements 8/8
100% Branches 2/2
100% Functions 1/1
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 314x     4x                               4x 396x   396x   396x 127x     269x    
import { hub } from '../hub'
 
import type { Rune } from '../../RuneHub'
import { Slot } from '../../RuneHub'
 
/**
 * Gets or creates a slot for a rune.
 * If the slot doesn't exist, creates it using the rune's custom cast function or default constructor.
 * @template T - The rune function type
 * @param rune - The rune to get or create a slot for
 * @returns The slot managing the rune's state
 * @example
 * ```ts
 * const count = () => 5
 *
 * const countSlot = slot(count)
 * countSlot.get() // 5
 * ```
 */
export function slot<T extends Rune> (rune: T): Slot<ReturnType<T>> {
  const currentHub = hub()
 
  const slot = currentHub.slots.get(rune)
 
  if (!slot) {
    return new Slot(rune, currentHub, false)
  }
 
  return slot as Slot<ReturnType<T>>
}