求助一道面试题

2021-05-21 00:01:56 +08:00
 erwin985211
// 实现一个 Test,可以按照以下方式调用
Test('tom') 
//  hi, tom
Test('tom').sleep(5).eat('dinner') 
// hi, tom // 等待 5s // weak up 5 // eat dinner
Test('tom').eat('dinner').eat('supper') 
//  hi, tom  // eat dinner // eat super
Test('tom').sleepFirst(5).eat('supper') 
// 等待 5s // wake up 5 // hi, tom //  eat super
1172 次点击
所在节点    问与答
7 条回复
DGideas
2021-05-21 00:13:02 +08:00
老哥,要求什么编程语言都没写,就放一道“面试题”在这里让大家随便帮你做,逗虫子呢?
renmu123
2021-05-21 00:19:35 +08:00
你就查一下怎么实现链式调用
CEBBCAT
2021-05-21 00:26:58 +08:00
简单的链式调用。Test() 返回一个指针,给指针定义 sleep eat sleepFirst 方法即可,这些方法同时也要返回传入的指针
eason1874
2021-05-21 00:44:09 +08:00
好消息! V2EX 和 Google 合作了!复制代码到搜索引擎,点击搜索就可以看到问题解析!

https://www.google.com/search?q=sleepFirst%285%29.eat%28%27supper%27%29+
belowfrog
2021-05-21 00:52:04 +08:00
function Test(name) {
const queue = [() => console.log(name)];

const result = {
sleepFirst,
sleep,
eat,
};

async function execute() {
while (queue.length) {
const fn = queue.shift();
await Promise.resolve(fn());
}
}

function sleepFirst(time) {
queue.unshift(
() =>
new Promise((resolve) => {
setTimeout(resolve, time * 1000);
})
);

return result;
}

function eat(food) {
queue.push(() => console.log(food));
return result;
}

function sleep(time) {
queue.push(
() =>
new Promise((resolve) => {
setTimeout(resolve, time * 1000);
})
);
return result;
}

Promise.resolve().then(() => execute());

return result;
}
suntorrent
2021-05-21 01:56:47 +08:00
这是考察啥?
erwin985211
2021-05-21 09:50:21 +08:00
@belowfrog 谢谢老哥,现在我处于有点想法但是写不出来的阶段

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/778245

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX