DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 8: Limit api calls

Question

Create a function called limitCalls that takes a function and a maximum number of calls as arguments. The function should return a closure that only invokes the original function up to the specified maximum number of times.

function logMessage(message) {
  console.log(message);
}

const limitedLogMessage = limitCalls(logMessage, 3);

limitedLogMessage('Hello'); // Output: Hello
limitedLogMessage('World'); // Output: World
limitedLogMessage('OpenAI'); // Output: Challenge
limitedLogMessage('Extra call'); // Output: Maximum number of calls reached!
Enter fullscreen mode Exit fullscreen mode

🤫 Check the comment below to see answer.

Top comments (1)

Collapse
 
dhrn profile image
Dharan Ganesan
function limitCalls(func, maxCalls) {
  let count = 0;

  return function (...args) {
    if (count < maxCalls) {
      count++;
      return func(...args);
    } else {
      console.log('Maximum number of calls reached!');
    }
  };
}
Enter fullscreen mode Exit fullscreen mode