Created
October 31, 2023 19:05
-
-
Save juliandavidmr/abc2f2654ab653307f555108c29ee9d6 to your computer and use it in GitHub Desktop.
State machine for a car engine
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, 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