这是一道常见的面试笔试题,可以考察我们对 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();