Toggle
Prompt
Write a function createToggle that takes any number of values and returns a function. Each time the returned function is called, it gives the next value in sequence, cycling back to the beginning after the last one.
Playground
You need a variable that remembers the current position in
the list between calls. A closure with an index variable
that starts at 0 works well.
The modulo operator % is how you cycle. (index + 1) % values.length wraps back to 0 when you reach the end of
the array.
Solution
Explanation
If you've solved the once question, this uses the same technique: a closure that remembers state between calls.
createToggle collects all the values into an array with ...values and creates an index variable starting at 0. It returns a function that closes over both. Every time you call that function, it grabs the value at the current index, moves the index forward, and returns the value.
The interesting part is how we make it cycle. When the index reaches the end of the array, it needs to wrap back to 0 instead of going out of bounds. That's what the modulo operator does:
index = (index + 1) % values.length;Modulo (%) gives you the remainder of a division. For createToggle('red', 'green', 'blue') where the array length is 3:
- Call 1: index is
0, returns'red', then(0 + 1) % 3 = 1 - Call 2: index is
1, returns'green', then(1 + 1) % 3 = 2 - Call 3: index is
2, returns'blue', then(2 + 1) % 3 = 0 - Call 4: index is back to
0, returns'red'again
When index + 1 equals the array length, the remainder is 0, so it wraps around. This is a really common trick in programming for anything that needs to loop through a fixed set of values. You'll see it in carousel implementations, round-robin schedulers, and game loops.
One more thing worth noting: each call to createToggle creates its own private index and values. So if you create two separate toggles, they don't share state. Calling one doesn't affect the other. That's closures at work -- each function gets its own little bubble of variables.
Where is this useful?
Toggling between light and dark themes, cycling through carousel slides, rotating through status values in a task manager, or stepping through options in a settings menu.