实现 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
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 810
Author 回答者: HSIKE
function LazyMan(name) {
console.log(`Hi! This is ${name}!`);
}
LazyMan.prototype.sleep = function (time) {
const timeInMiliSec = time * 1000;
const start = performance.now();
console.log(`Wait for ${time} seconds...`);
while (performance.now() - start <= timeInMiliSec) {}
console.log(`Wake up after ${time} seconds.`);
return this;
};
LazyMan.prototype.sleepFirst = function (time) {
return this.sleep(time);
};
LazyMan.prototype.eat = function (thing) {
console.log(`Eat ${thing}~~`);
return this;
};
Author 回答者: shfshanyue
function 方式
function LazyMan(name) {
if (!(this instanceof LazyMan)) {
return new LazyMan(name);
}
this.tasks = [];
// 添加初始问候任务
this.tasks.push(async () => {
console.log(`Hi! This is ${name}!`);
});
// 开始执行任务队列
this.runTasks();
return this;
}
LazyMan.prototype.runTasks = async function () {
setTimeout(async () => {
for (const task of this.tasks) {
await task();
}
}, 0);
};
LazyMan.prototype.sleep = function (seconds) {
this.tasks.push(async () => {
console.log(`等待${seconds}秒..`);
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
console.log(`Wake up after ${seconds}`);
});
return this;
};
LazyMan.prototype.sleepFirst = function (seconds) {
this.tasks.unshift(async () => {
console.log(`等待${seconds}秒..`);
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
console.log(`Wake up after ${seconds}`);
});
return this;
};
LazyMan.prototype.eat = function (food) {
this.tasks.push(async () => {
console.log(`Eat ${food}~`);
});
return this;
};
以及 class 方式
class LazyLazyMan {
constructor(name) {
this.tasks = [];
// 添加初始问候任务
this.tasks.push(async () => {
console.log(`Hi! This is ${name}!`);
});
// 开始执行任务队列
this.runTasks();
}
async runTasks() {
setTimeout(async () => {
for (const task of this.tasks) {
await task();
}
}, 0);
}
sleep(seconds) {
this.tasks.push(async () => {
console.log(`等待${seconds}秒..`);
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
console.log(`Wake up after ${seconds}`);
});
return this;
}
sleepFirst(seconds) {
this.tasks.unshift(async () => {
console.log(`等待${seconds}秒..`);
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
console.log(`Wake up after ${seconds}`);
});
return this;
}
eat(food) {
this.tasks.push(async () => {
console.log(`Eat ${food}~`);
});
return this;
}
}
function LazyMan(name) {
return new LazyLazyMan(name);
}