pocak
v0.1.1
Published
State machine
Downloads
10
Maintainers
Readme
Pocak
State machine
States:
// enum
const Turnstil = {
0: "Locked",
1: "Unlocked",
Locked: 0,
Unlocked: 1
};
Inputs or actions that are taken to change the state:
const coin = (current, states) => () => {
if (current === states.Locked) {
return states.Unlocked;
}
return current;
};
const push = (current, states) => () => {
if (current === states.Unlocked) {
return states.Locked;
}
return current;
};
To create a state machine you can use enums or arrays.
const [state, coin, push] = stateMachine(Turnstil, [coin, push]);
// OR
const [state, coin, push] = stateMachine(["Locked", "Unlocked"], [coin, push]);
// default state is the first enum or the first element in the array
state(); // => Locked
coin();
state(); // => Unlocked
push();
state(); // => Locked
Subscription to state changes is also possible:
state.subscribe((current, next) =>
console.log(`state transition from ${current} to ${next}`)
);