Implement a cycleOn function
cycleOn is a higher order utility function which helps you cycle through a list of values.
The generic implementation of cycleOn utility and can be extended to create other similar utilities like toggleOn (for two values).
1. Generic implementation
function cycleOn(values) { let activeIndex = 0;
function cycledFnImpl() { // if we have exceeded the limit for values length, reset the index if (activeIndex >= values.length) { activeIndex = 0; }
const result = values[activeIndex]; activeIndex++; return result; }
return cycledFnImpl;}
// Usage of the utility functionconst fruits = ['apple', 'mango', 'banana'];const cycleValue = cycleOn(fruits);
console.log(cycleValue()); // appleconsole.log(cycleValue()); // mangoconsole.log(cycleValue()); // banana// cycle restarts from here againconsole.log(cycleValue()); // apple
2. Variation of toggleOn
Usually cycleOn with only two values is referred as toggleOn, where you toggle between two state values.
import cycleOn from './src/cycleOn.js';
// cycleOn with two values can be also referred as toggleOnconst fruits = ['on', 'off'];const toggleOn = cycleOn(fruits);
console.log(toggleOn()); // onconsole.log(toggleOn()); // off// cycle restarts from here againconsole.log(cycleValue()); // 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 🫡.