Skip to content

Instantly share code, notes, and snippets.

@andrewgordstewart
Last active November 14, 2019 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewgordstewart/6d1025c1a404f800431b629878c21a89 to your computer and use it in GitHub Desktop.
Save andrewgordstewart/6d1025c1a404f800431b629878c21a89 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// You can click on the enabled (ie. blue) actions in the diagram, and view the current state in the "state" tab on the right.
// For simplicity, the `PROPOSE_NEW_OUTCOME`
// event uses nextOutcome() to assign the
// proposed outcome.
// You can proposedOutcome in the
// customActions object with the following
//
// proposedOutcome: function(c, event) {
// return event.outcome;
// },
// If you do this, you need to provide the
// outcome in the "EVENTS" tab
let counter = 0;
function nextOutcome() {
return `outcome ${++counter}`;
}
const currentOutcome = nextOutcome();
const proposedOutcome = currentOutcome;
const config = {
key: 'consensus-app',
initial: 'consensus',
context: {
numParticipants: 4,
votesRemaining: 0,
currentOutcome,
proposedOutcome
},
states: {
voting: {
on: {
VOTE: [
{
target: 'voting',
cond: 'moreVotesRequired',
actions: 'decrementVotesRequired'
},
{
target: 'consensus',
cond: 'consensusReached',
actions: ['decrementVotesRequired', 'updateOutcome']
}
],
PROPOSE_NEW_OUTCOME: {
target: 'voting',
actions: ['updateProposedOutcome', 'resetVotesRequired']
}
}
},
consensus: {
on: {
PROPOSE_NEW_OUTCOME: {
target: 'voting',
actions: ['updateProposedOutcome', 'resetVotesRequired']
}
}
}
}
};
const guards = {
moreVotesRequired: function(context) {
return context.votesRemaining > 1;
},
consensusReached: function(context) {
return context.votesRemaining == 1;
}
};
const customActions = {
updateProposedOutcome: {
type: 'xstate.assign',
assignment: {
proposedOutcome: function(c, event) {
return nextOutcome();
},
votesRemaining: function(context) {
return context.numParticipants - 1;
}
}
},
decrementVotesRequired: {
type: 'xstate.assign',
assignment: {
votesRemaining: function(context) {
return context.votesRemaining - 1;
}
}
},
updateOutcome: {
type: 'xstate.assign',
assignment: {
currentOutcome: function(context) {
return context.proposedOutcome;
}
}
}
};
const machine = Machine(config, { guards, actions: customActions });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment