Skip to content

Instantly share code, notes, and snippets.

@Ognian
Created December 27, 2019 13:07
Show Gist options
  • Save Ognian/a505c345279e4a05ab9881650c5f2da6 to your computer and use it in GitHub Desktop.
Save Ognian/a505c345279e4a05ab9881650c5f2da6 to your computer and use it in GitHub Desktop.
a function returning in graphviz dot language the state machine from https://github.com/nickuraltsev/finity
const printMachine = stateMachineConfig => {
// decorate=true -> as attribute is also useful, but colors are far better
const edgeTimerAttributes = ', color="darkgreen", fontcolor="darkgreen"'
const edgeSuccessAttributes = ', color="blue", fontcolor="blue"'
const edgeFailAttributes = ', color="red", fontcolor="red"'
let result = 'digraph {\n'
result += Object.getOwnPropertyNames(stateMachineConfig.states).reduce((acc, stateName) => {
let res = `${acc}`
const stateObject = stateMachineConfig.states[stateName]
const { timers, asyncActions } = stateObject // TODO events when I need them ...
res += timers.reduce(
(a, tim) => `${a} ${stateName} -> ${tim.transitions[0].targetState} [label=" timeout: ${tim.timeout} ms"${edgeTimerAttributes}]\n`,
''
)
res += asyncActions.reduce((a, asyncAct) => {
let r = `${a}`
const successState = asyncAct.successTrigger.transitions[0].targetState
const failureState = asyncAct.failureTrigger.transitions[0] ? asyncAct.failureTrigger.transitions[0].targetState : null
if (successState) {
r += ` ${stateName} -> ${successState} [label="${asyncAct.action.toString()} SUCCESS"${edgeSuccessAttributes}]\n`
}
if (failureState) {
r += ` ${stateName} -> ${failureState} [label="${asyncAct.action.toString()} FAILURE"${edgeFailAttributes}]\n`
}
return r
}, '')
return res
}, '')
result += '}'
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment