back to series

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).

Variation: Basic implementation

1. Generic implementation

./src/cycleOn.js
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 function
const fruits = ['apple', 'mango', 'banana'];
const cycleValue = cycleOn(fruits);
console.log(cycleValue()); // apple
console.log(cycleValue()); // mango
console.log(cycleValue()); // banana
// cycle restarts from here again
console.log(cycleValue()); // apple
Variation: Toggle on

2. Variation of toggleOn

Usually cycleOn with only two values is referred as toggleOn, where you toggle between two state values.

./src/toggleOn.js
import cycleOn from './src/cycleOn.js';
// cycleOn with two values can be also referred as toggleOn
const fruits = ['on', 'off'];
const toggleOn = cycleOn(fruits);
console.log(toggleOn()); // on
console.log(toggleOn()); // off
// cycle restarts from here again
console.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 🫡.