ES6 红绿灯 使用 class 和 promise

这是一道常见的面试笔试题,可以考察我们对 class 和 promise 的理解。 

class TrafficLight {
  constructor(redTime, yellowTime, greenTime) {
    this.redTime = redTime;
    this.yellowTime = yellowTime;
    this.greenTime = greenTime;
    this.running = false;
    this.currentColor = 'red';
    this.timer = null;
  }

  start() {
    if (this.running) return;
    this.running = true;
    this.timer = setTimeout(() => this.changeColor(), 0);
  }

  stop() {
    if (!this.running) return;
    this.running = false;
    clearTimeout(this.timer);
  }

  // 改变灯的时间
  changeDuration(color, duration) {
    switch (color) {
      case 'red':
        return this.redTime = duration;
      case 'yellow':
        return this.yellowTime = duration;
      case 'green':
        return this.greenTime = duration;
      default:
        return '';
    }
  }

  // 改变颜色
  changeColor() {
    const { redTime, yellowTime, greenTime, currentColor } = this;

    const nextColor = TrafficLight.getNextColor(currentColor);
    const duration = TrafficLight.getDuration(nextColor, redTime, yellowTime, greenTime);


    // 切换灯的颜色
    this.currentColor = nextColor;
    console.log(`The light color is ${this.currentColor}`);

    // 判断是否结束或继续下一次切换
    const promise = new Promise(resolve => setTimeout(resolve, duration));
    promise.then(() => this.running && this.changeColor());
  }

  // 获取下一次灯
  static getNextColor(color) {
    switch (color) {
      case 'red':
        return 'green';
      case 'yellow':
        return 'red';
      case 'green':
        return 'yellow';
      default:
        return 'red';
    }
  }

  // 获取灯的时长
  static getDuration(color, redTime, yellowTime, greenTime) {
    switch (color) {
      case 'red':
        return redTime * 1000;
      case 'yellow':
        return yellowTime * 1000;
      case 'green':
        return greenTime * 1000;
      default:
        return 0;
    }
  }
}



// 使用示例:


// 创建一个红绿灯对象
const light = new TrafficLight(10, 3, 15);

// 启动灯的变化
light.start();

// 改变绿灯时长
light.changeDuration('green', 5);

// 停止灯的变化
light.stop();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值