// Created on savesnippets.com · https://savesnippets.com/9sqDSyeppNOlYr function createMachine(config) { let current = config.initial; return { get state() { return current; }, can(event) { return event in (config.states[current]?.on ?? {}); }, send(event) { const transitions = config.states[current]?.on ?? {}; const next = transitions[event]; if (!next) throw new Error(`No transition '${event}' from '${current}'`); config.states[current]?.exit?.(); current = next; config.states[current]?.enter?.(); return current; }, }; } // Usage const machine = createMachine({ initial: 'idle', states: { idle: { on: { FETCH: 'loading' } }, loading: { on: { SUCCESS: 'done', ERROR: 'failed' }, enter: () => console.log('Loading…') }, done: { on: { RESET: 'idle' } }, failed: { on: { RESET: 'idle' } }, }, }); machine.send('FETCH'); // → loading machine.send('SUCCESS'); // → done