Created
July 17, 2022 03:43
-
-
Save suica/a8f495ee6a69550963456d13954ec9d1 to your computer and use it in GitHub Desktop.
Interview Coding Problems
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this problem is written by metis200, and can be found at https://github.com/metis200/FE-Exam | |
/** | |
* --- 问题描述 --- | |
* | |
* 实现一个 arrange 函数,可以进行时间和工作调度 | |
* | |
* --- 说明 --- | |
* | |
* - 本题需要自己实现测试用例 | |
* - 具体功能参考下列示例 | |
* - 在示例中调用到的方法都需要实现 | |
* - 下面示例中 `>` 表示在控制台中输出 (console.log) | |
* | |
* --- 示例 --- | |
* | |
* 示例一: | |
* `arrange('William').execute();` | |
* > William is notified | |
* | |
* 示例二: | |
* `arrange('William').wait(5).do('commit').execute();` | |
* > William is notified | |
* 等待 5s... | |
* > Start to commit | |
* | |
* 示例三: | |
* `arrange('William').waitFirst(3).do('push').execute();` | |
* 等待 3s... | |
* > William is notified | |
* > Start to push | |
* | |
*/ | |
function arrange(name) { | |
async function sleep(timeInSecond) { | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
resolve(); | |
}, timeInSecond * 1000); | |
}); | |
} | |
class Arrangement { | |
constructor(name) { | |
this.f = async () => { | |
console.log(`${name} is notified`); | |
} | |
} | |
waitFirst(time) { | |
const oldFn = this.f; | |
const newFn = () => { | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
resolve(oldFn()); | |
}, time * 1000); | |
}); | |
} | |
this.f = newFn; | |
return this; | |
} | |
wait(timeInSecond) { | |
const oldFn = this.f; | |
const newFn = () => { | |
return oldFn().then(() => { | |
return sleep(timeInSecond); | |
}); | |
} | |
this.f = newFn; | |
return this; | |
} | |
do(actionText) { | |
const oldFn = this.f; | |
const newFn = () => { | |
return oldFn().then(() => { | |
console.log(`Start to ${actionText}`); | |
}); | |
} | |
this.f = newFn; | |
return this; | |
} | |
execute() { | |
return this.f(); | |
} | |
} | |
return new Arrangement(name); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment