Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Number of times the callback needs to be called before executed

I got presented 4 interview questions and one of them is this:

Write a function after that 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading