Create a toggle function in JavaScript that accepts a list of arguments and toggles each of them when invoked in a cycle.
Example
let hello = toggle("hello"); hello() // "hello"; hello() // "hello"; let onOff = toggle("on", "off"); onOff() // "on" onOff() // "off" onOff() // "on"
The toggle function returns each value clockwise on each call of the function and the same can be done by returning a function from the toggle function forming a closure over the values to track the cycle.
const toggle = (...list) => { // to track the cycle let current = -1; const length = list.length; return function(){ //moves to next element, resets to 0 when current > length current = (current + 1) % length; return list[current]; } }
const hello = toggle("1", "2", "3"); console.log(hello()); // "1" console.log(hello()); // "2" console.log(hello()); // "3" console.log(hello()); // "1"