pocak

0.1.1 • Public • Published

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}`)
);

Package Sidebar

Install

npm i pocak

Weekly Downloads

2

Version

0.1.1

License

MIT

Unpacked Size

148 kB

Total Files

5

Last publish

Collaborators

  • jnszkr