I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
let blackbox = {
switchA: "off",
switchB: "off",
bulb:"off",
flickSwitchA : function() {
if (blackbox.switchA == "on"){
blackBox.switchA = "off"
}else if (blackbox.switchA == "off"){
blackbox.switchA = "on"
}else {console.log("A problem has occured with switch A")}
},
flickSwitchB : function(){
if(blackbox.switchB == "on"){
blackbox.switchB = "off"
}else if (blackbox.switchB == "off"){
blackbox.switchB = "on"
}else{console.log("A problem has occured with switch B")}
},
checkBulbStatus: function(){
if((blackbox.switchA == "on") && (blackbox.switchB == "on")){
blackbox.bulb = "on",
console.log("Bulb is on");
}else{
blackbox.bulb = "off";
console.log("Bulb is off");
}
}
}
blackbox.flickSwitchA()
blackbox.flickSwitchB()
blackbox.checkBulbStatus()
blackbox.checkBulbStatus()
how do I change this code to make it a factory creating backboxes that can also be changed from on to off each new black box needs to be able to be controlled independently each black box must have a on off and light which must be able to show the status of the switch
any help would be brilliant i know i can use arrays to do this but m not sure how to do this
function createBlackBox () {
return {
switchA: "off"
// .... rest of the object
};
}
const blackBox1 = createBlackBox();
const blackBox2 = createBlackBox();
blackbox1.flickSwitchA();
// ...and so on
(Edit: also, for future reference if you want to add more complex functionality to the state machine, look at xstate. Keeping it as simple as it is just in plain JS, as you’ve got now, is ideal, but if you add more states it’ll get hard to track & xstate is a v good library if you get to that point)
I need to create black boxes that can have switch a and b and can be turned on or off also I need the last part of the code to be able to check the status of each new black box.
I have managed to create the black boxes but they are all set to off and I need to be able to turn them on I am having trouble making the backboxes with the switches attached.
As I said above, you need to store the on/off variables in the factory function (createBlackBox) – at the minute you’re trying to refer to a variable blackBox that doesn’t exist