Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Last active May 8, 2022 18:14
Show Gist options
  • Save jtmthf/8ebb160a1fd7fdd0310027f9ae16091f to your computer and use it in GitHub Desktop.
Save jtmthf/8ebb160a1fd7fdd0310027f9ae16091f to your computer and use it in GitHub Desktop.
interface Machine<State extends string, Event extends string> {
initialState: State;
transition(currentState: State, event: Event): State;
}
interface MachineDefinition<State extends string, Event extends string> {
initialState: State;
states: Record<State, Record<Event, State>>;
}
function createMachine<State extends string, Event extends string>(
definition: MachineDefinition<State, Event>
): Machine<State, Event> {
return {
initialState: definition.initialState,
transition(currentState, event) {
const currentStateDefinition = definition.states[currentState];
const destinationState = currentStateDefinition[event];
if (!destinationState) {
return currentState;
}
return destinationState;
},
};
}
const machine = createMachine({
initialState: "green",
states: {
green: {
TIME_ELAPSED: "yellow",
},
yellow: {
TIME_ELAPSED: "red",
},
red: {
TIME_ELAPSED: "green",
},
},
});
let state = machine.initialState;
console.log("current state:", state);
state = machine.transition(state, "TIME_ELAPSED");
console.log("current state:", state);
state = machine.transition(state, "TIME_ELAPSED");
console.log("current state:", state);
state = machine.transition(state, "TIME_ELAPSED");
console.log("current state:", state);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment