Implement a sampling function
Sampling is a higher order utility function which invokes a function every n sample period. For other invocation which are not within the sampling period, it can return undefined.
1. Basic Implementation
function sampling(fn, n) { let invocations = 0;
function samplingFnImpl(...args) { invocation++; if (invocations % n !== 0) { return undefined; }
return fn.call(this, ...args); }
return samplingFnImpl;}
// Usage of the sampling utility functionconst sampledFn = sampling(() => { console.log('I will be called on every 3rd sampling period');}, 3);
sampledFn();sampledFn();sampledFn(); // yields logs here on 3th sample periodsampledFn();sampledFn();sampledFn(); // yields logs here on 6th sample period// ... so on
2. Variation with last result
In this variation, if the function is invoked in non-sampling period, we simply need to return the last result saved during the sampling period invocation of function.
function sampling(fn, n) { let invocations = 0; let lastResult = undefined;
function samplingFnImpl(...args) { invocation++; if (invocations % n !== 0) { // simply return last saved result instead of undefined return lastResult; }
// save result of function invocation lastResult = fn.call(this, ...args); return lastResult; }
return samplingFnImpl;}
// Usage of the sampling utility functionconst sampledFn = sampling(() => { console.log('I will be called on every 3rd sampling period');}, 2);
sampledFn();sampledFn(); // yields logs here on 2nd sample periodsampledFn();sampledFn(); // yields logs here on 4th sample periodsampledFn();sampledFn(); // yields logs here on 6th sample period// ... so on
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 🫡.