@@ -30,11 +30,11 @@ export class StateMachine<
3030
3131 // initialize the state-machine
3232 constructor (
33- _init : STATE ,
33+ protected init : STATE ,
3434 protected transitions : ITransition < STATE , EVENT , CALLBACK [ EVENT ] > [ ] = [ ] ,
3535 protected readonly logger : ILogger = console ,
3636 ) {
37- this . _current = _init ;
37+ this . _current = init ;
3838 }
3939
4040 addTransitions ( transitions : ITransition < STATE , EVENT , CALLBACK [ EVENT ] > [ ] ) : void {
@@ -109,8 +109,6 @@ export class StateMachine<
109109
110110 /**
111111 * Generate a Mermaid StateDiagram of the current machine.
112- *
113- * Order your transitions so that the first and last are terminals
114112 */
115113 toMermaid ( title ?: string ) {
116114 const diagram : string [ ] = [ ] ;
@@ -120,7 +118,7 @@ export class StateMachine<
120118 diagram . push ( "---" ) ;
121119 }
122120 diagram . push ( "stateDiagram-v2" ) ;
123- diagram . push ( ` [*] --> ${ String ( this . transitions [ 0 ] . fromState ) } ` ) ;
121+ diagram . push ( ` [*] --> ${ String ( this . init ) } ` ) ;
124122
125123 this . transitions . forEach ( ( { event, fromState, toState } ) => {
126124 const from = String ( fromState ) ;
@@ -129,8 +127,11 @@ export class StateMachine<
129127 diagram . push ( ` ${ from } --> ${ to } : ${ evt } ` ) ;
130128 } ) ;
131129
132- const last = this . transitions [ this . transitions . length - 1 ] ;
133- diagram . push ( ` ${ String ( last . toState ) } --> [*]` ) ;
130+ // find terminal states
131+ const ts = new Set < STATE > ( ) ;
132+ this . transitions . forEach ( ( { toState } ) => ts . add ( toState ) ) ;
133+ this . transitions . forEach ( ( { fromState } ) => ts . delete ( fromState ) ) ;
134+ ts . forEach ( ( state ) => diagram . push ( ` ${ String ( state ) } --> [*]` ) ) ;
134135
135136 return diagram . join ( "\n" ) ;
136137 }
0 commit comments