Skip to content

Instantly share code, notes, and snippets.

@juliandavidmr
Created October 31, 2023 19:05
Show Gist options
  • Save juliandavidmr/abc2f2654ab653307f555108c29ee9d6 to your computer and use it in GitHub Desktop.
Save juliandavidmr/abc2f2654ab653307f555108c29ee9d6 to your computer and use it in GitHub Desktop.
State machine for a car engine
import { createMachine, assign } from "xstate";
interface Context {
maxGears: number;
fuelLevel: number;
currentGear: number;
}
const engineCarMachine = createMachine<Context>(
{
id: "fetch",
initial: "ENGINE_OFF",
context: {
maxGears: 6,
fuelLevel: 0,
currentGear: 0,
},
states: {
ENGINE_OFF: {
on: {
FILL_FUEL: {
actions: assign({
fuelLevel: 100,
}),
},
START_ENGINE: {
target: "ENGINE_ON",
},
},
},
ENGINE_ON: {
on: {
TURN_OFF_ENGINE: {
target: "ENGINE_OFF",
},
UP_GEAR: {
cond: 'canUpGear',
target: "ENGINE_ON",
actions: assign((context) => ({
currentGear: context.currentGear + 1
}))
},
DOWN_GEAR: {
cond: 'canDownGear',
target: "ENGINE_ON",
actions: assign((context) => ({
currentGear: context.currentGear - 1
}))
},
},
},
},
},
{
guards: {
canUpGear: (context, event) =>
context.currentGear < context.maxGears,
canDownGear: (context, event) =>
context.currentGear > 0,
},
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment