实现一个LazyMan,可以按照以下方式调用:
LazyMan(“Hank”)输出:
Hi! This is Hank!
LazyMan(“Hank”).sleep(10).eat(“dinner”)输出
Hi! This is Hank!
//等待10秒…
Wake up after 10
Eat dinner~
LazyMan(“Hank”).eat(“dinner”).eat(“supper”)输出
Hi This is Hank!
Eat dinner~
Eat supper~
LazyMan(“Hank”).sleepFirst(5).eat(“supper”)输出
//等待5秒
Wake up after 5
Hi This is Hank!
Eat supper
实现过程如下:
function LazyMan(name) {
return new _Lazyman(name)
}
class _Lazyman {
constructor(name) {
this.tasks = []
let task = (name => () => {
console.log(`Hi! This is ${name}`)
this.next()
})(name)
this.tasks.push(task)
setTimeout(() => {
this.next()
}, 0);
}
next() {
let task = this.tasks.shift()
task && task()
}
sleep(time) {
let task = (time => () => {
setTimeout(() => {
console.log(`Wake up after ${time} s!`)
this.next()
}, time);
})(time)
this.tasks.push(task)
return this
}
eat(someThing) {
let task = (someThing => () => {
console.log(`Eat ${someThing}`)
this.next()
})(someThing)
this.tasks.push(task)
return this
}
sleepFirst(time) {
let task = (time => () => {
setTimeout(() => {
console.log(`Wake up after ${time} s!`)
this.next()
}, time);
})(time)
this.tasks.unshift(task)
return this
}
}
LazyMan('Hank').sleep(3).eat('food').sleepFirst(2)