Home > other >  js switch statement follows a pattern
js switch statement follows a pattern

Time:11-15

I have a switch statement with 33 cases, each corresponding to a column in a 2d array. The values in the array is the row that will be transitioned too. Is there a cleaner way to write this? each case follows the pattern for letter in alphabet dfarow = [dfarow][n 1]

function FEN2datumType(fen, dfa) {    

//                 alpabet length 33                            
// exampleDFA = [[1, 0, 1, 2, 1, 0, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 2, 1, 0, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0]], 
//              [[1, 1, 2, 2, 1, 0, 1, 2, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 2, 1, 0, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0]],
//              [[2, 1, 2, 2, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1, 1, 1, 2, 1, 0, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 2]]

dfarow = 0; // start state
for (char in fen) { 
  switch (char) {
    case "r":      //alpabet 0
      dfarow = dfa[dfarow][0];
      break;
    case "n":
      dfarow = dfa[dfarow][1];
      break;
    case "b":
      dfarow = dfa[dfarow][2];
      break;
    case "q":
      dfarow = dfa[dfarow][3];
      break;
    case "k":
      dfarow = dfa[dfarow][4];
      break;
    case "p":
      dfarow = dfa[dfarow][5];
      break;
.....etc...

this is the first DFA I have written, I open to suggestions. my alphabet is a FEN string (Forsyth–Edwards Notation chess) 33 possible chars. exampleDFA has 3 transition states and I have not implemented an accepting state (I was thinking of putting an identifier in the 34th column of the DFA array i.e. if (dfa[dfarow][34] == 1) //accept)

CodePudding user response:

You can create object for the alphabet:

var alphabet = { r:0, n:1, b:2, .... }

and then you can call alphabet object in for loop:

for (char in fen) { 
  dfarow = dfa[dfarow][alphabet[char]];
}

  • Related