back to series

Implement a limit function

Limit is a higher order utility function which limits the invocation of a function to at most n times. After further invocation (after n), it should yield the same last result.

This is a generic implementation of limit utility and can be extended to create other similar utilities like limitOnce, limitTwice etc.

Variation: Basic implementation

1. Generic implementation

./src/limit.js
function limitFnInvocation(fn, limit) {
let result = undefined;
let invocations = 0;
function limitedFnImpl(...args) {
// if we have exceeded the limit for invocations, simply return the last result
if (invocations >= limit) {
return result;
}
result = fn.call(this, ...args);
invocations++;
return result;
}
return limitedFnImpl;
}
// Usage of the utility function
const limitedFn = limitFnInvocation(() => {
console.log('I am called');
}, 3);
limitedFn();
limitedFn();
limitedFn();
// Won't yield any logs from this point on
limitedFn();
Variation: Limit Once

2. Variation of limitOnce

./src/limitOnce.js
import limitFnInvocation from './src/limit.js';
// Usage of the generic utility function to create limit once
const limitOnce = limitFnInvocation(() => {
console.log('I am called');
}, 1);
limitOnce();
// Won't yield any logs from this point on
limitOnce();
Variation: Limit Twice

3. Variation of limitTwice

./src/limitTwice.js
import limitFnInvocation from './src/limit.js';
// Usage of the generic utility function to create limit twice
const limitTwice = limitFnInvocation(() => {
console.log('I am called');
}, 2);
limitTwice();
limitTwice();
// Won't yield any logs from this point on
limitTwice();

Further Reading

I strongly encourage you to explore and tackle additional questions in my Closure Questions for Frontend Interviews blog series.

By doing so, you can enhance your understanding and proficiency with closures, preparing you to excel in your upcoming frontend interviews.

Wishing you best. Happy Interviewing 🫡.