Skip to content

j0u1/finity

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@j0u1/finity

Lightweight finite state machine (FSM) library for TypeScript.

npm wakatime Socket Badge

Install

bun add @j0u1/finity
# or
npm install @j0u1/finity

Usage

Single transition per state:

import { createMachine } from "@j0u1/finity"

const traffic = createMachine({
  initial: "red",
  transitions: {
    red: "yellow",
    yellow: "green",
    green: "yellow",
  },
})

traffic.current                 // "red"
traffic.moveTo("yellow")        // "yellow"
traffic.canChangeTo("green")    // true
traffic.canChangeTo("red")      // false

Multiple transitions per state:

const order = createMachine({
  initial: "pending",
  transitions: {
    pending: ["success", "fail"],
    success: [],
    fail: [],
  },
})

order.canChangeTo("success")   // true
order.canChangeTo("fail")      // true
order.moveTo("success")        // "success"

API

createMachine(config)

Creates a new state machine.

Parameter Type Description
config.initial string Initial state
config.transitions Record<string, string | string[]> Map of state transitions

Returns an object with:

  • current — current state
  • moveTo(state) — transitions to the given state. Throws if transition is not allowed.
  • canChangeTo(state) — returns true if transition to given state is possible from current state

License

MIT