Skip to content

Instantly share code, notes, and snippets.

@erickeno
Last active January 24, 2020 23:42
Show Gist options
  • Save erickeno/31f1b48f47f8d8e5d7d6a8f7c43fd504 to your computer and use it in GitHub Desktop.
Save erickeno/31f1b48f47f8d8e5d7d6a8f7c43fd504 to your computer and use it in GitHub Desktop.
microwave machine
const openMic = {
initial: 'idle',
states: {
idle: {
on: {
ADD_THIRTY_SEC: { actions: 'addThirtySec', target: 'running' },
ADD_TIME: { actions: 'addTime' },
SET_TIME: { actions: 'setTime' },
START: { target: 'running', cond: ({ countdown }) => countdown !== 0 },
},
},
running: {
invoke: {
id: 'startCountdown',
src: () => callback => {
const id = setInterval(() => callback('DEC'), 1000);
return () => clearInterval(id);
},
},
on: {
'': [{ target: 'done', cond: 'isZero' }],
DEC: { actions: 'dec' },
ADD_THIRTY_SEC: { actions: 'addThirtySec' },
PAUSE: 'paused',
OFF: 'done',
},
},
paused: { on: { START: 'running', OFF: 'done' } },
done: {
activities: ['beep'],
on: {
CLEAR: { target: 'idle', actions: 'reset' },
},
},
},
};
const microwave = new Machine(
{
id: 'microwave',
initial: 'open',
context: { countdown: 0 },
states: {
closed: {
...openMic,
on: {
OPEN: '#microwave.open',
CLEAR: { target: '.idle', actions: 'reset' },
},
},
open: {
on: {
CLOSE: 'closed',
CLEAR: {
target: '',
actions: 'reset',
cond: ({ countdown }) => countdown !== 0,
},
},
},
},
},
{
actions: {
addThirtySec: assign({ countdown: ({ countdown }) => countdown + 30000 }),
addTime: assign({
countdown: ({ countdown }, { time }) => countdown + (time ? time : 0),
}),
dec: assign({ countdown: ({ countdown }) => countdown - 1000 }),
reset: assign({ countdown: () => 0 }),
setTime: assign({ countdown: (_, { time }) => (time ? time : 0) }),
},
activities: {
beep: () => {
const id = setInterval(() => console.log('BEEP'), 2000);
return () => clearInterval(id);
},
},
guards: { isZero: ({ countdown }) => countdown <= 0 },
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment