JS Built-ins
Closuresadvanced

Closures β€” Rate limiter

πŸ“– Usage Example
function makeLimiter(maxCalls) {
  return (fn) => {
    let count = 0
    return (...args) => count++ < maxCalls ? fn(...args) : undefined
  }
}
const limiter = makeLimiter(2)
const limited = limiter(() => 'ok')
limited()  // β†’ 'ok'
limited()  // β†’ undefined (limit exceeded)

Closures keep a private counter per wrapper, enabling precise control over how many times a function is allowed to execute.

Limit Function Call Frequency

Create a wrapper that restricts how many times a function can be called in total.

Challenge: Create a makeLimiter(maxCalls) function that takes a maximum number of allowed calls. It returns a function that accepts another function to be wrapped. The returned wrapper function will execute the original function up to maxCalls times. After maxCalls executions, it returns undefined without calling the function.

Example:

const limiter = makeLimiter(2)
const limited = limiter(() => 'called')
limited()  // 'called' (call 1)
limited()  // 'called' (call 2)
limited()  // undefined (exceeded limit)
πŸ’‘ Hints (3)
  • β€’ Create a counter in closure to track calls
  • β€’ Return a wrapper that checks the counter before executing
  • β€’ Return undefined when limit is exceeded