当前位置:   article > 正文

js-generator-状态机及控制状态机_js 状态机

js 状态机

使用一个变量维护状态


let open = true
let clock = () => {
  open = !open
  return !open
}
console.log(clock())
console.log(clock())

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

使用generator自身状态


let clock2 = function* () {
  while(true) {
    yield true
    yield false
  }
}
let gen = clock2()
console.log(gen.next().value)
console.log(gen.next().value)
console.log(gen.next().value)
console.log(gen.next().value)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

控制状态机1:使用互相来控制

let clock3 = function* () {
  let r
  while(r = (yield 'isOpen?')) {
    yield true
    yield false
  }
}
let r
let gen = clock3()
gen.next() // 启动
r = gen.next(1) // t 开启
console.log(r.value)
r = gen.next() // f
console.log(r.value)
r = gen.next() // ask
console.log(r.value)
r = gen.next(1) // t 开启
console.log(r.value)
r = gen.next() // f
console.log(r.value)
r = gen.next() // ask
console.log(r.value)
r = gen.next(0) // 关闭
console.log(r.value)
r = gen.next() // undefined
console.log(r.value)
r = gen.next() // undefined
console.log(r.value)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

控制状态机2:使用return来控制

let clock4 = function* () {
  while(true) {
    yield true
    yield false
  }
}
let r
let gen = clock4()
r = gen.next() // t
console.log(r.value)
r = gen.next() // f
console.log(r.value)
r = gen.return() // undefined
console.log(r.value)
r = gen.next() // undefined
console.log(r.value)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/696587
推荐阅读
相关标签
  

闽ICP备14008679号