skip to Main Content

I was asked the following question in a JavaScript interview. I was unable to answer it. Please help!

const printString = (string, callback) => {
    setTimeout(() => {
        console.log(string);
        callback();
    }, Math.random() * 1000);
};

Call function printString three times with characters ‘a’, ‘b’ and ‘c’ and write a callback function such that a, b and c are printed in sequential order. Use the callback function however you want.

Any assistance is appreciated 🙂

4

Answers


  1. To print the characters ‘a’, ‘b’, and ‘c’ in sequential order, you can use the callback function to chain the calls to printString. Here’s an example implementation:

    const printString = (string, callback) => {
        setTimeout(() => {
            console.log(string);
            callback();
        }, Math.random() * 1000);
    };
    
    const printInOrder = (strings, index) => {
        if (index === strings.length) {
            return;
        }
        printString(strings[index], () => {
            printInOrder(strings, index + 1);
        });
    };
    
    printInOrder(['a', 'b', 'c'], 0);
    

    In this implementation, we define a new function printInOrder that takes an array of strings and an index as input. The index is used to keep track of which string to print next. If the index is equal to the length of the array, we stop the recursion.

    Inside the printInOrder function, we call printString with the current string and a callback function that calls printInOrder with the next index. This way, we chain the calls to printString and ensure that the strings are printed in sequential order.

    Finally, we call printInOrder with the array of strings and an initial index of 0 to start the recursion.

    Login or Signup to reply.
  2. You could wrap the call to printString in a promise and pass res as a callback. When callback is executed inside the setTimeout, the promise gets resolved and it will move to the next item in the loop.

    const printString = (string, callback) => {
      setTimeout(() => {
        console.log(string);
        callback();
      }, Math.random() * 1000);
    };
    
    const inputs = ['a', 'b', 'c'];
    
    (async () => {
      for (const n of inputs) {
        await new Promise(res => printString(n, res));
      }
    })()
    Login or Signup to reply.
  3. The question is not completely clear to me since nothing is mentioned if we can use promise. I presume we can use it , so my solution will be to create a promise and then in the resolve we can call the callback

    function printVal(val) {
      console.log(val)
    }
    
    const printString = async(string, callback) => {
      return new Promise(resolve => setTimeout(() => {
        resolve(callback(string));
      }, Math.random() * 1000))
    
    };
    
    
    const caseFunc = async() => {
      const items = ['a', 'b', 'c'];
      for (item of items) {
        const val = await printString(item, printVal);
      }
    }
    caseFunc()
    Login or Signup to reply.
  4. There is no need to use Promises, the simplest answer is to chain the printString method itself as a callback.

    const printString = (string, callback) => {
        setTimeout(() => {
            console.log(string);
            callback();
        }, Math.random() * 1000);
    };
    
    printString('a', 
          () => printString('b', 
              () => printString('c', () => undefined)));

    Since its an interview question, the Math.random() is probably to deflect your mind into thinking that they will be called out of order, but they will be not.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search