I have just written this code for toggling between two possible states of an object.
// This can't change, and only ever has two states
const MODES = {
ON: 'ON',
OFF: 'OFF'
}
// this is my method
const toggleMode = currentMode => {
const modes = Object.values(MODES);
const newMode = modes.find(mode => mode !== currentMode);
return newMode
};
// toggle state
const firstState = MODES.ON;
console.log(firstState);
const secondState = toggleMode(firstState);
console.log(secondState);
const thirdState = toggleMode(secondState)
console.log(thirdState)
Is this a good way of toggling between the two states? I'm concerned it's less readable than the verbose if one state, then pick the other, else pick the current state
. But this way also means that so long as we know there's only two states, then nothing needs to be hardcoded in the function doing the toggling.