1.0.3 ā€¢ Published 3 years ago

ts-state-machines v1.0.3

Weekly downloads
10
License
MIT
Repository
github
Last release
3 years ago

TypeScript State Machines

What is this? šŸ§

A TypeScript library to create state machines with type safe transitions. The available state transitions for the current state will autocomplete and type check.

This is accomplished by making each state immutable, with each transition method returning the next state.

Examples šŸš€

Stoplight

const Stoplight = StateMachine({
  initialState: "red",
  states: {
    red: {
      timer: "green",
    },
    green: {
      timer: "yellow",
    },
    yellow: {
      timer: "red",
    },
  },
} as const);

const stoplight = Stoplight();

// TypeScript will infer this to be 'red';
stoplight.state;

// TypeScript will infer this to be 'green';
stoplight.timer().state;

// TypeScript will infer this to be 'yellow';
stoplight.timer().timer().state;

Promiselike

const Promiselike = StateMachine({
  initialState: "pending",
  states: {
    pending: {
      start: "loading",
    },
    loading: {
      resolve: "resolved",
      reject: "rejected",
    },
    resolved: {},
    rejected: {},
  },
} as const);

const promise = Promiselike();

// TypeScript will infer this to be 'resolved';
promise.start().resolve().state;

// TypeScript will infer this to be 'rejected';
promise.start().reject().state;

Maintaining a reference to the latest state

const Stoplight = StateMachine({
  initialState: "red",
  states: {
    red: {
      timer: "green",
    },
    green: {
      timer: "yellow",
    },
    yellow: {
      timer: "red",
    },
  },
} as const);

let stoplight: StateMachineInstance<typeof Stoplight.config>;

stoplight = Stoplight();
stoplight.state; // 'red'

stoplight = stoplight.timer();
stoplight.state; // 'green'

stoplight = stoplight.timer();
stoplight.state; // 'yellow'

stoplight = stoplight.timer();
stoplight.state; // 'red'

Installation & Usage šŸ“¦

  1. Add this package to your project:
    • yarn add ts-state-machines

Highlights

šŸŽ Zero run time dependencies

šŸŖ Isomorphic / Universal -- safe to run in any JS context: the browser or on a server

šŸ¦¶ Small footprint 279 B minified and gzipped

Contributing šŸ‘«

PR's and issues welcomed! For more guidance check out CONTRIBUTING.md

Licensing šŸ“ƒ

See the project's MIT License.