Complete the createToggle function Problem #4
Question: Write the createToggle() function and fulfill the functionality.
const lightSwitch = createToggle('ON', 'OFF');
console.log(lightSwitch.getState()); // "ON"
lightSwitch.toggle();
console.log(lightSwitch.getState()); // "OFF"
lightSwitch.toggle();
console.log(lightSwitch.getState()); // "ON"
lightSwitch.reset();
console.log(lightSwitch.getState()); // "ON"
Answer:
function createToggle(onState, offState){
let state = onState;
return {
getState(){
return state;
},
toggle(){
state = state==onState?offState:onState;
},
reset(){
return onState;
}
};
}