Last active
May 8, 2022 18:14
-
-
Save jtmthf/8ebb160a1fd7fdd0310027f9ae16091f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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