back to series Implement a limit function Mar 26, 2024
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 function limitFnInvocation ( fn , limit ) {
function limitedFnImpl ( ... args ) {
// if we have exceeded the limit for invocations, simply return the last result
if (invocations >= limit) {
result = fn. call ( this , ... args);
// Usage of the utility function
const limitedFn = limitFnInvocation (() => {
console. log ( 'I am called' );
// Won't yield any logs from this point on
Variation: Limit Once import limitFnInvocation from './src/limit.js' ;
// Usage of the generic utility function to create limit once
const limitOnce = limitFnInvocation (() => {
console. log ( 'I am called' );
// Won't yield any logs from this point on
Variation: Limit Twice import limitFnInvocation from './src/limit.js' ;
// Usage of the generic utility function to create limit twice
const limitTwice = limitFnInvocation (() => {
console. log ( 'I am called' );
// Won't yield any logs from this point on
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 🫡.