实现一个 LazyMan
问题
实现一个 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
以此类推。
答案
class LazyPeople { isHoldOn = false waitTasks = [] timer = null constructor(name) { this.sayHi(name) } prepareRunTask() { if (this.timer) { clearTimeout(this.timer) } this.timer = setTimeout(() => { this.runTask() }, 0); } sayHi(name) { this.waitTasks.push(() => console.log(`Hi! This is ${name}!`)) this.prepareRunTask() return this } sleepFirst(time) { this.waitTasks.unshift(() => { return new Promise((resolve) => setTimeout(resolve, time * 1000)) }) this.prepareRunTask() return this } eat(someThing) { this.waitTasks.push(() => console.log(`Eat ${someThing}~`)) this.prepareRunTask() return this } async runTask() { const task = this.waitTasks.slice(0) for (let i = 0; i < task.length; i++) { await task[i]() this.waitTasks.shift() } this.waitTasks.length = [] } sleep(time) { this.waitTasks.push(() => { return new Promise((resolve) => setTimeout(resolve, time * 1000)) }) this.prepareRunTask() return this } } function LazyMan(name) { return new LazyPeople(name) } // test LazyMan("Hank") LazyMan("Hank").sleep(10).eat("dinner") LazyMan("Hank").eat("dinner").eat("“supper”") LazyMan("Hank").sleepFirst(5).eat('food')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论