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.
1. Generic implementation
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 functionconst limitedFn = limitFnInvocation(() => { console.log('I am called');}, 3);
limitedFn();limitedFn();limitedFn();// Won't yield any logs from this point onlimitedFn();
2. Variation of limitOnce
import limitFnInvocation from './src/limit.js';
// Usage of the generic utility function to create limit onceconst limitOnce = limitFnInvocation(() => { console.log('I am called');}, 1);
limitOnce();// Won't yield any logs from this point onlimitOnce();
3. Variation of limitTwice
import limitFnInvocation from './src/limit.js';
// Usage of the generic utility function to create limit twiceconst limitTwice = limitFnInvocation(() => { console.log('I am called');}, 2);
limitTwice();limitTwice();// Won't yield any logs from this point onlimitTwice();
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 🫡.