Skip to content

Instantly share code, notes, and snippets.

@scytalezero
Last active August 9, 2021 13:17
Show Gist options
  • Save scytalezero/7745fd94ff4b72002e2a422ef2144db8 to your computer and use it in GitHub Desktop.
Save scytalezero/7745fd94ff4b72002e2a422ef2144db8 to your computer and use it in GitHub Desktop.
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const increment = key => context => context[key]++
const decrement = key => context => context[key]--
const cartActions = {
ADD_FACILITY: {
target: 'not-empty',
actions: increment('addFacility'),
},
REMOVE_FACILITY: {
target: 'not-empty',
actions: decrement('addFacility'),
},
ADD_ADDON: {
target: 'not-empty',
actions: increment('addAddon'),
},
CANCEL_ADDON: {
target: 'not-empty',
actions: decrement('addAddon'),
},
CANCEL_ALL: {
target: 'empty',
},
}
const fetchMachine = Machine({
id: 'cart',
initial: 'empty',
context: {
addFacility: 0,
addAddon: 0,
cancelAddon: 0,
reactivateAddon: 0,
switchAddon: 0,
},
states: {
empty: {
entry: 'clearCart',
on: {
...cartActions,
}
},
'not-empty': {
on: {
EMPTY: {
target: 'empty',
cond: 'isEmpty',
},
CHECKOUT: {
target: 'empty',
cond: 'notEmpty',
},
...cartActions,
},
meta: {
test: 'test',
},
},
},
},
{
actions: {
clearCart: context => Object.keys(context)
.forEach(k => context[k] = 0),
},
guards: {
isEmpty: context => Object.keys(context).reduce((acc, key) => acc + context[key], 0) < 1,
notEmpty: context => Object.keys(context).reduce((acc, key) => acc + context[key], 0) > 0,
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment