001: 实现下面这道题目中的machine函数
metro2703 opened this issue · 1 comments
metro2703 commented
function machine(name) {
}
machine('thewall').execute()
// start thewall
machine('thewall').do('eat').execute();
// start thewall
// thewall eat
machine('thewall').wait(5).do('eat').execute();
// start thewall
// wait 5s(这里等待了5s)
// thewall eat
machine('thewall').waitFirst(5).do('eat').execute();
// wait 5s
// start thewall
// thewall eat
metro2703 commented
function machine(name){
return new Machine(name);
}
function Machine(name){
this.name = name;
this.action = [];
this.init();
}
Machine.prototype.init = function () {
this.action.push(`start ${this.name}`);
}
Machine.prototype.execute = function () {
for (var i = 0; i < this.action.length; i++) {
console.log(this.action[i]);
if(this.action[i].indexOf('wait')){
var time = this.action[i].slice(5,6);
// await new Promise((resolve)=>{
// setTimeout(resolve,time*1000);
// })
// 怎么实现停留5秒?懵逼了
}
}
}
Machine.prototype.do = function (thing) {
this.action.push(`${this.name} ${thing}`);
return this;
}
Machine.prototype.wait = function (second) {
this.action.push(`wait ${second}s`);
return this;
}
Machine.prototype.waitFirst = function (firstSecond) {
this.action.unshift(`wait ${firstSecond}s`);
return this;
}
machine('zhangsan').wait(5).do('eat').execute()