/ Gists / Toggle fn - closure in closure (fn returns fn)
On gists

Toggle fn - closure in closure (fn returns fn)

JavaScript

toggle.js Raw #

const toggle = (...list) => 
{
    // To track the cycle.
    let current = -1;
    const length = list.length;
    return function () 
    {
        // Increment current and used modulo to cycle back to the start.
        current = (current + 1) % length;

        // Returing the current element.
        return list[current];
    };
};

const toggleFunction = toggle("ON","OF");
console.log(toggleFunction()); // Prints "ON"
console.log(toggleFunction()); // Prints "OF"
console.log(toggleFunction()); // Prints "ON"