Last active
October 17, 2023 14:32
-
-
Save 0xjcf/88277b7aa4f122f2957fb39c5e2c95c9 to your computer and use it in GitHub Desktop.
Traffic Light State Machine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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