// 实现一个 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
1
DGideas 2021-05-21 00:13:02 +08:00
老哥,要求什么编程语言都没写,就放一道“面试题”在这里让大家随便帮你做,逗虫子呢?
|
2
renmu123 2021-05-21 00:19:35 +08:00 via Android
你就查一下怎么实现链式调用
|
3
CEBBCAT 2021-05-21 00:26:58 +08:00
简单的链式调用。Test() 返回一个指针,给指针定义 sleep eat sleepFirst 方法即可,这些方法同时也要返回传入的指针
|
4
eason1874 2021-05-21 00:44:09 +08:00 2
好消息! V2EX 和 Google 合作了!复制代码到搜索引擎,点击搜索就可以看到问题解析!
https://www.google.com/search?q=sleepFirst%285%29.eat%28%27supper%27%29+ |
5
belowfrog 2021-05-21 00:52:04 +08:00 1
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; } |
6
suntorrent 2021-05-21 01:56:47 +08:00
这是考察啥?
|
7
erwin985211 OP @belowfrog 谢谢老哥,现在我处于有点想法但是写不出来的阶段
|