[Javascript] Coding interview problem: Scheduler functional way

Implement a job scheduler which takes in a function f and an integer n, and calls f after nmilliseconds

 

function curry (fn) {
  const arity = fn.length;
  return function $curry(...args) {
    if (args.length < arity) {
        return $curry.bind(null, ...args);
    }
    
    return fn.call(null, ...args);
  }
}

const setScheduler = curry((ms, fn) => {
  return setTimeout(() => fn(), ms) 
});

const halfSecond = setScheduler(500);

console.log('before'); 
halfSecond(() => console.log('Timeup')); 
setTimeout(() => console.log('after'), 600); 
// |A          A: before
// |-----B     B: Timeup
// |------C    C: after

 

posted @ 2019-03-13 06:05  Zhentiw  阅读(245)  评论(0)    收藏  举报