0

I have the following state diagram that is for validating whether a string matches a format. state diagram

I would like to recreate this language matching fsm in xstate. The machine should return true for ac, abc, abbbbbc etc and otherwise false. It should have exactly the same output as the regex expression string.match(/^ab*c$/) !== null;

I currently have the following:

const machine = Machine({
    initial: 'start',
    states: {
        start: {
            on: {A: 'state1'}
        },
        state1: {
            on: {
                B: 'state1',
                C: 'end'
            }
        },
        end: {}
    }
});

Is there a way through actions and context I can check if a string matches this language fsm through it reaching the end state.

Of course I could just use regex but I have simplified the problem for the purpose of this so question. The actual language I want to parse is not regular and requires pda / context. I just want to know the structure of using xstate for language / string parsing.

Ben
  • 3,160
  • 3
  • 17
  • 34
  • 1
    I'm gonna give this a go :) Join me here if you wish: https://codesandbox.io/s/xstate-simple-regex-style-parser-pww28 – Glutnix Mar 11 '20 at 23:09
  • @Glutnix Looks very interesting, a lot more complex than I thought though. I guess xstate isn't really built for language parsing. Instead I have landed on a method of switching through a ts enum. – Ben Mar 13 '20 at 19:00

1 Answers1

0
const checkRegex =(content,event)=>{
if(event.match(/^ab*c$/) !== null){
context.valid =true;
}
}
const regexMachine = Machine({
initial: 'state1',
states: {
    state1:{
        on:{
          VALIDATE: {
                target:"state2"
               }
        }
     }
    state2: {
        invoke:{
              src:(context,event)=>checkRegex(event)},
              onDone:{target:"end"}
              onError:{target:"state1"}
    },
    end: {
         type: "final"
     }
}
});

Component Usage:

const [current,send] = useMachine(regexMachine);

send("VALIDATE","aaabbbcc");
Vijay122
  • 884
  • 8
  • 12