Skip to content

Instantly share code, notes, and snippets.

@0xjcf
Last active October 17, 2023 14:32
Show Gist options
  • Save 0xjcf/88277b7aa4f122f2957fb39c5e2c95c9 to your computer and use it in GitHub Desktop.
Save 0xjcf/88277b7aa4f122f2957fb39c5e2c95c9 to your computer and use it in GitHub Desktop.
Traffic Light State Machine
import { createMachine, send } from "xstate";
createMachine({
id: "traffic-light-machine",
type: "parallel",
states: {
trafficSignal: {
initial: "greenLight",
states: {
greenLight: {
on: {
YIELD: {
target: "yellowLight",
actions: send("HURRY"),
},
STOP: {
target: "redLight",
actions: send("WALK")
},
},
},
redLight: {
on: {
GO: {
target: "greenLight",
actions: send("HALT"),
},
},
},
yellowLight: {
on: {
STOP: {
target: "redLight",
actions: send("WALK"),
},
},
},
},
},
walkSignal: {
initial: "redLight",
states: {
redLight: {
on: {
WALK: {
target: "whiteLight",
actions: send("STOP"),
},
},
},
whiteLight: {
on: {
HURRY: {
target: "yellowLight",
actions: send("YIELD"),
},
HALT: {
target: "redLight",
},
},
},
yellowLight: {
on: {
HALT: {
target: "redLight",
actions: send("GO"),
},
},
},
},
},
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment