Skip to content
generated from denorg/starter

A no-frills state machine module. ⚙️

License

Notifications You must be signed in to change notification settings

sidiousvic/motor

Repository files navigation

⚙ Motor

A no-frills finite state machine module.


Deno CI GitHub Contributors TypeScript semantic-release



Start the motor

import { motor } from "https://deno.land/x/motor/mod.ts";

type Gears = "stopped" | "paused" | "playing" | "loading";

type Events = "SELECT" | "LOAD" | "PLAY" | "PAUSE" | "STOP";

const musicPlayerMotor: MotorSpec<Gears, Events> = {
  gear: "stopped",
  transmission: {
    stopped: {
      on: { LOAD: "loading" },
    },
    paused: {
      on: { PLAY: "playing", STOP: "stopped" },
    },
    loading: {
      on: { PLAY: "playing", STOP: "stopped" },
    },
    playing: {
      on: { PAUSE: "paused", STOP: "stopped" },
    },
  },
};

const { fire, gear } = motor(musicPlayer);

 assertEquals(gear(), "stopped");

fire("LOAD");

 assertEquals(gear(), "loading");

fire("PLAY");

 assertEquals(gear(), "playing");

fire("PAUSE");

 assertEquals(gear(), "paused");

fire("STOP");

 assertEquals(gear(), "stopped");

Hook to changes in state

let counter = 0;

const count = () => (counter += 1);

const { fire, gear, hook } = motor(musicPlayerMotor);

 assertEquals(gear(), "stopped");

hook(count);

fire("LOAD");

 assertEquals(counter, 1);

fire("PLAY");

 assertEquals(counter, 2);

fire("STOP");

 assertEquals(counter, 3);

🧰 Development

Run tests:

deno test --allow-read

📄 License

MIT

About

A no-frills state machine module. ⚙️

Resources

License

Stars

Watchers

Forks

Packages

No packages published