A library for finite state machines.
Using npm:
npm install --save-dev wstate
In Node.js:
const stateMachine = require("wstate");
A state machine can be constructed using:
import { createMachine } from "wstate";
const fsm = createMachine({
init: "stand",
states: {
stand: {
down: "squat",
up: [
"jump",
(event, state) => {
// handle jump callback
},
],
},
squat: {
down: "stand",
},
jump: {
down: "cutdown",
},
cutdown: {
up: "stand",
},
},
onFail: (event, state) => {
// Handle the callback of abnormal state machine
},
});
... which creates an object with a current state property:
fsm.state
... methods to transition to a different state:
fsm.up()
fsm.down()
... along with the following helper methods:
fsm.is(s)
- return true if states
is the current statefsm.can(t)
- return true if transitiont
can occur from the current statefsm.cannot(t)
- return true if transitiont
cannot occur from the current statefsm.transitions()
- return list of transitions that are allowed from the current statefsm.allTransitions()
- return list of all possible transitionsfsm.allStates()
- return list of all possible states
import { useMachine, createMachine } from "wstate";
const fsm = createMachine({
init: "stand",
states: {
stand: {
down: "squat",
up: [
"jump",
(event, state) => {
// handle jump callback
},
],
},
squat: {
down: "stand",
},
jump: {
down: "cutdown",
},
cutdown: {
up: "stand",
},
},
onFail: (event, state) => {
// Handle the callback of abnormal state machine
},
});
function App() {
const [current, change] = useMachine(fsm);
return (
<div className="App">
<span>当前的状态是{current}</span>
<button onClick={() => change("down")}> 跳跃</button>
</div>
);
}
A state machine consists of a set of States
- stand
- cutdown
- squat
- jump
A state machine changes state by using Transitions
- up
- dowm
A state machine can also have arbitrary Data and Methods
Multiple instances of a state machine can be created using a State Machine Factory
The state machine does not own the state, it just defines the state and defines the state transition
State machines are very useful because they never cross the boundary. No matter what the input is, if the machine thinks it is feasible, then it will transition to the correct state, otherwise depending on your configuration, your state machine will stop transitioning or throw an error.
👤 keenzhang
- Github: @keenzhang
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Give a ⭐️ if this project helped you!
Copyright © 2021 keenzhang.
This project is MIT licensed.