共计 1936 个字符,预计需要花费 5 分钟才能阅读完成。
实现下面这道题中的 machine 函数
function machine() {
}
machine(‘ygy’).execute()
// start ygy
machine(‘ygy’).do(‘eat’).execute();
// start ygy
// ygy eat
machine(‘ygy’).wait(5).do(‘eat’).execute();
// start ygy
// wait 5s(这里等待了 5s)
// ygy eat
machine(‘ygy’).waitFirst(5).do(‘eat’).execute();
// wait 5s
// start ygy
// ygy eat
原型写法
维护一个数组,异步就 push 函数,不是异步就 push 字符串
function machine(name) {
if(!(this instanceof machine)){
return new machine(name)
}
this.name = name
this.logs = []
this.logs.push(`start ${name}`)
}
machine.defer = function(time){
const times = time
return function(){
console.log(`wait ${times}s`)
return new Promise((resolve)=>{
setTimeout(()=>{resolve()},times*1000)
})
}
}
machine.prototype.execute = async function(){
const logs = this.logs
if(logs.length > 0){
for(let i=0; i<logs.length; i++){
if(typeof(logs[i]) === ‘function’){
await logs[i]()
}else {
console.log(logs[i])
}
}
}
};
machine.prototype.do = function(argument){
this.logs.push(`${this.name} ${argument}s`)
return this
};
machine.prototype.wait = function(item){
this.logs.push(machine.defer(item))
return this
};
machine.prototype.waitFirst = function(item){
this.logs.unshift(machine.defer(item))
return this
};
es6 写法
维护一个 queue 队列数组,里面全部是构造函数,第一个参数代码是否异步,第二个是 callback
function machine(name) {
return new Action(name)
}
const defer = (time, callback) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(callback())
}, time * 1000)
})
}
class QueueItem {
constructor(defer, callback) {
this.defer = defer;
this.callback = callback;
}
}
class Action {
queue = []
constructor(name) {
this.name = name;
this.queue.push(new QueueItem(0, () => console.log(`start ${this.name}`)))
}
do(eat) {
this.queue.push(new QueueItem(0, () => console.log(`${this.name} ${eat}`)))
return this;
}
wait(time) {
this.queue.push(new QueueItem(time, () => console.log(`wait ${time}s`)))
return this;
}
waitFirst(time) {
this.queue.unshift(new QueueItem(time, () => console.log(`wait ${time}s`)))
return this;
}
async execute() {
while(this.queue.length > 0) {
const curItem = this.queue.shift();
if (!curItem.defer) {
curItem.callback();
continue;
}
await defer(curItem.defer, curItem.callback)
}
}
}
比较
数组每一个都是构造函数有点浪费空间