JavaScript状态机处理字符串

用状态机实现:字符串“abcabx”的解析

function match(str){
  let state = start;
  for(let s of str){
    state = state(s);
  }
  return state === end;
}

function start(s){
  return s === 'a' ? foundA : start;
}
function end(s){
  return end;
}
function foundA(s){
  return s === 'b' ? foundB : start(s);
}
function foundB(s){
  return s === 'c' ? foundC : start(s);
}
function foundC(s){
  return s === 'a' ? foundA2 : start(s);
}
function foundA2(s){
  return s === 'b' ? foundB2 : start(s);
}
function foundB2(s){
  return s === 'x' ? end : foundB(s);
}

使用状态机完成”abababx”的处理。

function match(str){
  let state = start;
  for(let s of str){
    state = state(s);
  }
  return state === end;
}
function start(s){
  return s === 'a' ? foundA : start;
}
function end(s){
  return end;
}
function foundA(s){
  return s === 'b' ? foundB: start(s);
}
function foundB(s){
  return s === 'a' ? foundA2: start(s);
}
function foundA2(s){
  return s === 'b' ? foundB2: start(s);
}
function foundB2(s){
  return s === 'a' ? foundA3: start(s);
}
function foundA3(s){
  return s === 'b' ? foundB3: start(s);
}
function foundB3(s){
  return s === 'x' ? end: foundB2(s);
}

猜你喜欢

转载自blog.csdn.net/lixiaosenlin/article/details/107868022