This page is part of a static HTML representation of TriTarget.org at https://tritarget.org

Micro State Machine

Sukima17th September 2020 at 3:27pm

This is a micro implementation of the Simple State Machine idea for cases when all you need is very simple state tracking and action management.

See also, CSS based view states.

This has tests and an ES6 import implementation if interested.

function transitionMachine(
  machine,
  { value: currentState } = {},
  event
) {
  ({ type: event = event } = event);
  const A = i => Array.isArray(i) ? i : [i];
  let state = currentState ?? machine.initial;
  let transition = machine.states[state].on?.[event]
    ?? machine.on?.[event]
    ?? { target: state };
  let value = transition?.target ?? transition;
  let changed = value !== currentState;
  let actions = [
    ...(
      changed
        ? A(machine.states[currentState]?.exit ?? [])
        : []
    ),
    ...A(transition.actions ?? []),
    ...(
      changed
        ? A(machine.states[value]?.entry ?? [])
        : []
    )
  ];
  let states = value.split(':');
  let inState = states.reduce(
    (a, i) => ({ ...a, [i]: true }),
    {}
  );
  return { value, changed, actions, states, inState };
}