遇到一个有趣的题目,做个笔记
实现一个arrange函数,可以进行时间和工作调度
//[> …]表示调用函数后的打印内容
//arrange(‘William’).execute();
//> William is notified
//arrange(‘William’).do(‘commit’).execute();
//>William is notified
//>Start to commit
//arrange(‘William’).wait(5).do(‘commit’).execute();
//>William is notified
//等待5秒
//>Start to commit
//arrange(‘William’).waitFirst(5).do(‘push’).execute();
//等待5秒
//>William is notifed
//>Start to push
function arrange(){
//此处写代码逻辑
}
可以通过链式调用来实现这个问题。每个方法都返回一个对象,该对象包含当前的状态和一系列要执行的方法
function arrange(name) {
const state = {
name: name,
actions: [],
waitFirstTime: 0
};
return {
execute() {
if (state.waitFirstTime > 0) {
setTimeout(() => this.executeAfterWait(), state.waitFirstTime * 1000);
} else {
this.executeAfterWait();
}
},
executeAfterWait() {
console.log(`${state.name} is notified`);
state.actions.forEach(action => {
if (action.type === 'wait') {
setTimeout(action.fn, action.time * 1000);
} else {
action.fn();
}
});
},
do(task) {
state.actions.push({
type: 'task',
fn: () => console.log(`Start to ${task}`)
});
return this;
},
wait(time) {
state.actions.push({
type: 'wait',
time: time,
fn: () => console.log(`Waited for ${time} seconds`)
});
return this;
},
waitFirst(time) {
state.waitFirstTime = time;
return this;
}
};
}
// 测试用例
arrange('William').execute();
arrange('William').do('commit').execute();
arrange('William').wait(5).do('commit').execute();
arrange('William').waitFirst(5).do('push').execute();