Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created May 28, 2024 07:13
Show Gist options
  • Save Kcko/666772ac65f087517cfa31a3e911b773 to your computer and use it in GitHub Desktop.
Save Kcko/666772ac65f087517cfa31a3e911b773 to your computer and use it in GitHub Desktop.
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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment