实现一个arrange函数,可以进行时间和工作调度

实现一个arrange函数" title="range函数">range函数,可以进行时间和工作调度

//  [  >  …  ]  表示调用函数后的打印内容

// arrange('William');

// > William is notified

// arrange('William').wait(5).do('commit');

// > William is notified

// 等待 5 秒

// > Start to commit

// arrange('William').waitFirst(5).do('push');

// 等待 5 秒

// > Start to push

// > William is notified

这不是一个简单的问题。
一道面试题,网上没找到答案;我试了很久没做对;
初步判断需要实现一个任务队列;
然后通过一些方式让一些任务立即执行,延后执行

我很想通过这个demo 学会调度方面的知识;再次感谢

回答

尝试写了一下,用了Proxy以及用了两个数组做了简单的优先级,结果和期望一致:

const arrange = name => {

const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

const list = [];

const priorityList = [];

let _priority = false;

list.push(() => console.log(`${name} is notified`));

const chain = new Proxy({}, {

get(_, prop) {

return data => {

const [_, method, priority = _priority] = /^(\w+?)(First)?$/[Symbol.match](prop);

_priority = priority;

if (method === 'wait') {

(priority ? priorityList : list).push(async () => await wait(data * 1000));

} else if(method === 'do') {

(priority ? priorityList : list).push(() => console.log(`Start to ${data}`));

}

return chain;

}

}

});

setTimeout(async () => {

for (let func of priorityList) {

await func();

}

for (let func of list) {

await func();

}

}, 0)

return chain;

};

// arrange('William');

// arrange('William').wait(5).do('commit');

arrange('William').waitFirst(5).do('push');

实现一个arrange函数,可以进行时间和工作调度

class Arrange {

index = 0

promises: Array<string | Promise<any>> = []

constructor(info: string) {

this.promises = [`${info} is notified`]

this.index++

}

// 出现 `waitFirst` 从前面载入

waitFirst = (s: number) => {

this.promises.unshift(new Promise(resolve => setTimeout(resolve, s * 1000)))

this.index = 1

return this

}

// 出现 `wait` 消除 `waitFirst` 效果

wait = (s: number) => {

this.promises.splice(this.index, 0, new Promise(resolve => setTimeout(resolve, s * 1000)))

this.index = this.promises.length

return this

}

do = (task: 'commit' | 'push') => {

switch (task) {

case 'commit': this.promises.splice(this.index, 0, `Start to commit`); break;

case 'push': this.promises.splice(this.index, 0, 'Start to push'); break;

default: break;

}

this.index++

return this

}

run = async (log = (info: any) => {}) => {

for (let i = 0; i < this.promises.length; i++) {

const info = await Promise.resolve(this.promises[i]);

log && info && log(info)

}

return this

}

}

const arrange = (s = '') => {

const a = new Arrange(s)

setTimeout(() => {

console.time('run:')

a.run(function (info) {

console.timeLog('run:', info)

})

}, 0);

return a

}

// arrange('William');

// arrange('William').wait(5).do('commit');

arrange('William').waitFirst(5).do('push');

以上是 实现一个arrange函数,可以进行时间和工作调度 的全部内容, 来源链接: utcz.com/a/61912.html

回到顶部