Objects instead of switches
Switch example (complex):
function Switch_RPS_Eval_Game(alice, bob) {
// If Alice and Bob chose the same choice, we will output a tie
if (alice === bob) {
console.log("Alice and Bob tie")
}
else {
let isAliceWin; // variable to determine if Alice won
// Switch on Alice choice
switch (alice) {
case "Rock": switch (bob) {
case "Scissors": isAliceWin = true;
break;
default: isAliceWin = false;
}
break;
case "Scissors": switch (bob) {
case "Paper": isAliceWin = true;
break;
default: isAliceWin = false;
}
break;
case "Paper": switch (bob) {
case "Rock": isAliceWin = true;
break;
default: isAliceWin = false;
}
break;
}
if (isAliceWin) {
console.log("Alice Wins!");
}
else {
console.log("Bob Wins!");
}
}
}
Object example:
const RPS_rules = {
Rock: { Scissors: true },
Scissors: { Paper: true },
Paper: { Rock: true }
};
function createRuleGame(rulesObj) {
return function (alice, bob) {
// If Alice and Bob chose the same choice, we will output a tie
if (alice === bob) {
console.log("Alice and Bob tie")
}
else {
// variable to determine if alice won
let isAliceWin = rulesObj[alice][bob];
if (isAliceWin) {
console.log("Alice Wins!");
}
else {
console.log("Bob Wins!");
}
}
}
}
const Object_RPS_Eval_Game = createRuleGame(RPS_rules);