0.0.5 • Published 1 year ago

ts-machine v0.0.5

Weekly downloads
-
License
-
Repository
github
Last release
1 year ago

ts-machine min size minzip size

A simple state machine with good enough build time typechecking support.

npm i ts-machine

Example

Here is a simple stoplight example:

const lightMachine = defineMachine<null>()
  .states(["green", "yellow", "red"])
  .transitions({
    green: ["yellow"],
    yellow: ["red"],
    red: ["green"],
  })
  .events(["SWITCH"])
  .on("SWITCH", ["green"], () => "yellow")
  .on("SWITCH", ["yellow"], ({}) => "red")
  .on("SWITCH", ["red"], () => "green");

const light = lightMachine.create("red", null);

assert.equal(light.state, "red");
light.emit("SWITCH");
await waitForState(light, "green");
light.emit("SWITCH");
await waitForState(light, "yellow");
light.emit("SWITCH");
await waitForState(light, "red");

More examples can be found in the tests directory:

Helpers

waitForState

import { type Machine } from "ts-machine";

export function waitForState<M extends Machine<any, any>>(
  machine: M,
  state: M["state"] | M["state"][],
  next: boolean = true
) {
  return new Promise<void>((resolve) => {
    if (machine.state === state) {
      resolve();
      return;
    }
    const unsubscribe = machine.subscribe((machine) => {
      if (machine.state === state) {
        unsubscribe();
        resolve();
        return;
      }

      if (next) {
        unsubscribe();
        throw new Error(
          `Expected state ${
            typeof state === "string" ? state : (state as string[]).join(",")
          } but got ${machine.state}`
        );
      }
    });
  });
}
0.0.5

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago