Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
How to limit function calls in JS?

I need a function limitCalls (fn, maxCalls) that takes a function fn and returns a new function that can be called no more than the number of times specified in maxCalls. Test example:

 it('limitCalls', () => {
const makeIncrement = () => {
  let count = 0;

  return () => {
    count += 1;
    return count;
  };
};

const limitedIncrementA = limitCalls(makeIncrement(), 3);

expect(limitedIncrementA()).toBe(1);
expect(limitedIncrementA()).toBe(2);
expect(limitedIncrementA()).toBe(3);
expect(limitedIncrementA()).toBe(undefined);
expect(limitedIncrementA()).toBe(undefined);

const limitedIncrementB = limitCalls(makeIncrement(), 1);

expect(limitedIncrementB()).toBe(1);
expect(limitedIncrementB()).toBe(undefined);
expect(limitedIncrementB()).toBe(undefined);

});

I have:

var calls = 0;
export default function limitCalls(fn, maxCalls) {
  if (calls >= maxCalls) {
    return undefined;
  }
  calls += 1;
  return fn();
}

And error is limitedIncrementA is not a function. Help me please to realise it.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Instead of conditionally returning a function, always return a function that conditionally executes the fn callback:

function limitCalls(fn, maxCalls) {
  let count = 0;
  
  return function(...args) {
    return count++ < maxCalls ? fn(...args) : undefined;
  }
}

const limited = limitCalls(console.log, 3);

limited('one');
limited('two');
limited('three');
limited('four');

about 4 years ago · Juan Pablo Isaza Report

0

In this snippet, limitedIncrementA isn't indeed a function. See this:

/* You're calling makeIncrement,
   so you're passing its return to 'limitCalls'
 */
const limitedIncrementA = limitCalls(makeIncrement(), 3);

/* Here, considering that makeIncrement exists,
   you're passing a reference to this functions,
   which can be called inside 'limitCalls'
 */
const limitedIncrementB = limitCalls(makeIncrement, 3);

So, supposing that makeIncrement returns 1, 2, 3, ..., your current code is equivalent to:

limitCalls(1, 3);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!