由于面试官在国外,遂采用的视频面试。 1.自我介绍; 2.职业规划; 3.为什么选择字节跳动; 4.最近的项目中有什么是你优化的地方。 5.编程题: JS实现一个带并发限制的异步调度器Scheduler,保证同时运行的任务最多有两个。完善代码中Scheduler类,使得以下程序能正确输出。 class Scheduler {  add(promiseCreator) { ... }  // ...}const timeout = (time) => new Promise(resolve => {  setTimeout(resolve, time)})const scheduler = new Scheduler()const addTask = (time, order) => {  scheduler.add(() => timeout(time))    .then(() => console.log(order))}addTask(1000, '1')addTask(500, '2')addTask(300, '3')addTask(400, '4')// output: 2 3 1 4// 一开始,1、2两个任务进入队列// 500ms时,2完成,输出2,任务3进队// 800ms时,3完成,输出3,任务4进队// 1000ms时,1完成,输出1// 1200ms时,4完成,输出4我的答案:class Scheduler {  constructor () {    this.list = [];    this.count = 0;  }  add(promiseCreator) {    return new Promise(resolve => {      // 加入任务队列      this.list.push(() => {        resolve(Promise.resolve(promiseCreator()).then(s => {          // 当前任务结束后,执行下一个任务          this.count--;          this.start();          return s        }));      });      // 执行当前任务      this.start();    })  }  start () {    // 最多两个同时进行的任务    if (this.count < 2) {      this.count++;      this.list[0] && this.list[0]();      this.list.shift();    }  }}const timeout = (time) => new Promise(resolve => {  setTimeout(resolve, time)})const scheduler = new Scheduler();const addTask = (time, order) => {  scheduler.add(() => timeout(time)).then(() => console.log(time, 'time, order', order))}addTask(1000, '1');addTask(500, '2');addTask(300, '3');addTask(400, '4');// output: 2 3 1 4// 一开始,1、2两个任务进入队列// 500ms时,2完成,输出2,任务3进队// 800ms时,3完成,输出3,任务4进队// 1000ms时,1完成,输出1// 1200ms时,4完成,输出4   很遗憾代码没有通过用例,不知道哪里出错了😭,能否有大神指点下,让我死明白。
点赞 12
评论 9
全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-11 17:39
小呆呆的大鼻涕:卧槽,用户彻底怒了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务