I recently got an interview question, that I failed to answer correctly. Here it goes:
Write an implementation of a function
callAfter
that enables ANY function to be called after some specified duration. The output of the function should remain the same. The function should have > following syntax:Example 1: Let's say you have a function called
sum
like so:function sum(a, b) { console.log('Sum is: ', a + b); }
Now you should be able to execute:
sum.callAfter(5000, 8, 9);
This should invoke the function
sum
after 5 seconds with parameters 8 and 9. Output: 'Sum is: 17'.Example 2: For a function
difference
with the following implementation:function difference(a, b) { console.log('Difference is: ', a-b); }
You should be able to execute:
difference.callAfter(4000, 8, 6);
This should invoke the function
difference
after 4 seconds with parameters 8 and 6. Output: 'Difference is: 2'.
NOTE: I am aware that I could execute a function after n seconds using something like:
var delay_func = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
However, I was asked to attach a callAfter
'sub-function' with every function to facilitate the call:
<function_name>.callAfter(milliseconds, param1, param2, ...);
You can do it by adding a method to the function constructor's prototype object. That way any created function can inherit that method. It's referred to as prototypal inheritance:
Function.prototype.callAfter = function(delay, ...args) {
setTimeout(() => this(...args), delay)
};