
Linca
@linca
既然刚刚在 Notes 里写了个面试题,忍不住怀念一下自己的第一次面试(which 挂了)。
当时没写出来(确实菜),虽然场下不紧张了马上就写出来了。
题目: 实现一个 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: string) {
const jobs: (
{ type: "sleep"; time: number } | { type: "eat"; what: string } | { type: "say"; what: string }
)[] = [
{
type: "say",
what: `Hi! This is ${name}!`,
},
];
function sleepFirst(this: ReturnType<typeof LazyMan>, time: number) {
jobs.unshift({
type: "sleep",
time,
});
return this;
}
function eat(this: ReturnType<typeof LazyMan>, what: string) {
jobs.push({
type: "eat",
what,
});
return this;
}
function sleep(this: ReturnType<typeof LazyMan>, time: number) {
jobs.push({
type: "sleep",
time,
});
return this;
}
setTimeout(async () => {
for (const job of jobs) {
switch (job.type) {
case "say":
console.log(job.what);
break;
case "sleep":
await new Promise((r) => setTimeout(r, job.time * 1000));
console.log(`Wake up after ${job.time}`);
break;
case "eat":
console.log(`Eat ${job.what}~`);
break;
}
}
}, 0);
return {
sleep,
sleepFirst,
eat,
};
}
// LazyMan('Hank');
// LazyMan('Hank').sleep(10).eat('dinner');
// LazyMan('Hank').eat('dinner').eat('supper');
// LazyMan("Hank").sleepFirst(5).eat("supper");