I got presented 4 interview questions and one of them is this:
Write a function
afterthat takes the number of times the callback needs to be called before being executed as the first parameter and the callback as the second parameter.function after(count, func) { // Implement the 'after' function } var called = function() { console.log("hello") }; var afterCalled = after(3, called); afterCalled(); // -> nothing is printed afterCalled(); // -> nothing is printed afterCalled(); // -> 'hello' is printed
The way I solved the problem is this:
function after(count, cBack) {
localStorage.setItem("aCount", count);
return function () {
let currCount = localStorage.getItem("aCount");
if (currCount == 1) {
cBack();
} else {
localStorage.setItem("aCount", --currCount);
}
};
}
let called = function () {
console.log("hello");
};
let afterCalled = after(5, called);
afterCalled();
afterCalled();
afterCalled();
afterCalled();
afterCalled();
I mean, the code works as intended but I have a feeling that localStorage is not the way. Am I missing somethig? Is there something in callback functions that I can use or I ‘should’ use to solve this problem? If so, what should I look up?
>Solution :
They probably expected you to use the closure formed by calling after (see comments):
let after = (count, callback) => {
return () => {
// Has our count reached one?
if (count <= 1) {
// Yes, call the callback
callback();
} else {
// No, decrement the count
--count;
}
};
};
let called = function () {
console.log('hello')
};
let afterCalled = after(5, called);
afterCalled();
afterCalled();
afterCalled();
afterCalled();
afterCalled();
The count parameter continues to exist as long as the function that after returns exists, because the function after returns is a closure over the context where it was created. So you can use that to remember the number of times called.