首页 > 编程语言 > 详细

[XState] Replace Enumerated States with a State Machine

时间:2020-01-18 18:25:14      阅读:67      评论:0      收藏:0      [点我收藏+]

numerating the possible states of a function is a sound way to write a function, but it is imperative and could benefit from abstraction. We can do this with a state machine.

A state machine formalizes how we enumerate states and transitions. For the sake of clarity and to emphasize the core concepts, I will be overly verbose with my code in this lesson.

In this lesson, we‘ll replace the state enum with individual state objects. We‘ll also replace our events toggle() and break() with events TOGGLE and BREAK. I‘ll also demonstrate the usefulness of the Machine‘s initialState getter and the transition method. Lastly, I‘ll show what happens when we pass erroneous states or events into our machine.

 

// enumeratds states
const STATE = {
  LIT: "lit",
  UNLIT: "unlit",
  BROKEN: "broken"
};

function lightBulb() {
  let state = STATE.UNLIT;

  return {
    state() {
      return state;
    },
    toggle() {
      switch (state) {
        case STATE.LIT:
          state = STATE.UNLIT;
          break;
        case STATE.UNLIT:
          state = STATE.LIT;
          this.break;
      }
    },
    break() {
      state = STATE.BROKEN;
    }
  };
}

const bulb = lightBulb();
const log = () => {
  console.log(bulb.state());
};

bulb.toggle();
bulb.break();
log(); // broken

 

Using xstate:

const { Machine } = require("xstate");

const lit = {
  // ‘on‘ keyword present events
  on: {
    TOGGLE: "unlit",
    BROKEN: "broken"
  }
};
const unlit = {
  on: {
    TOGGLE: "lit",
    BROKEN: "broken"
  }
};
const broken = {
  // you can leave it empty, the same as final state
  //type: "final"
};

const states = { lit, unlit, broken };

const lightBulb = Machine({
  id: "lightBulb",
  initial: "unlit",
  strict: true,
  states
});

console.log(lightBulb.transition("broken", "TOGGLE").value); // broken
console.log(lightBulb.transition("lit", "TOGGLE").value); // unlit
console.log(lightBulb.transition("unlit", "TOGGLE").value); // lit

 

[XState] Replace Enumerated States with a State Machine

原文:https://www.cnblogs.com/Answer1215/p/12209701.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!