Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

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

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

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

//  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 学会调度方面的知识;再次感谢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

尝试写了一下,用了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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...