Home > Net >  How would I structure a class for a universal remote that sends an On/Off command to various devices
How would I structure a class for a universal remote that sends an On/Off command to various devices

Time:07-11

I want to create a universal remote class where multiple devices are connected to it. I know they wont extend from the remote but unsure how I would send a power off /on command to all of them.

I was thinking like:

const tv = new TV()
tv.isOn // gives false
const light = new Light()
light.isOn // gives false
const xbox = new Xbox()
xbox.isOn // gives false
const remote = new Remote()
remote.on()
tv.isOn // gives true
light.isOn // gives true
xbox.isOn // gives true

So now if you check like the TV object to see if it was on it would be or the lights etc.

In my head

class TV extends Remote

sounds dumb. but I cant think of a way where just calling the remote class would change all the other objects. I'm fairly new to coding so any help would be appreciated

CodePudding user response:

Extending the remote won't help you since you will still have different instances (extending a class will only provide the methods from that class but will not share the state of it with other instances).

A solution for your problem would be to make the on (toggle would be a better name to toggle between on and off) function accept a list of dependencies that would be updated (you still need to know the instances of the devices that you want to toggle on/off since you need to pass them to that function).

The toggle function can just negate the previous value this.isOn = !this.isOn depending on your needs (right now you control if all of them are on/off, by passing the boolean they will all be in sync all the time -- except for when they are instantiated with different states).

class Device {
    constructor(state = false) {
        this.isOn = state;
    }

    toggleState(state) {
        this.isOn = state;
    }
}

class TV extends Device {}
class Xbox extends Device {}
class Light extends Device {}

class Remote {
    toggle(state, devices = []) {
        devices.forEach(device => {
            device.toggleState(state);
        })
    }
}

const tv = new TV();
const xbox = new Xbox();
const light = new Light();

const remote = new Remote();

console.log(tv.isOn);
console.log(xbox.isOn);
console.log(light.isOn);

remote.toggle(true, [ tv, xbox, light ]);

console.log(tv.isOn);
console.log(xbox.isOn);
console.log(light.isOn);

Is this what you are looking for?

  • Related