Challenge: Solution Review
This lesson will explain the solution to the problem from the last coding challenge.
Solution #
// old interfaceclass TruthAndDare {constructor(){this.turn = Math.floor(Math.random() * 2) + 1;}Getturn(){if(this.turn == 1){this.turn = 2}else{this.turn = 1}return this.turn}playGame(playerOnename,playerTwoname){if(this.Getturn() == 1){return`${playerOnename}'s turn`}else{return `${playerTwoname}'s turn`}}}// new interfaceclass NewTruthAndDare {constructor(randomValue){this.turn = randomValue}newplayGame(playerOnename,playerTwoname){if((this.turn % 2) == 0){return `${playerOnename}'s turn`}else{return `${playerTwoname}'s turn`}}}// Adapter Classclass Adapter {constructor(randomValue) {const newGame = new NewTruthAndDare(randomValue)this.playGame = function(playerOnename,playerTwoname) {return newGame.newplayGame(playerOnename,playerTwoname)};}}const obj = new Adapter(6) //pass even/odd values here to see varying resultsconsole.log(obj.playGame("Ross","Chandler"))
Explanation #
In the code, we have a TruthAndDare class, which has a playGame function that decides which player’s turn it is depending on the turn variable. The constructor initializes turn to either 1 or 2 randomly.
The turn variable is accessed through the Getturn function.
Getturn(){
if(this.turn == 1){
this.turn = 2
}else{
this.turn = 1
}
return this.turn
}
If the value of turn is 1 the function sets it to 2 and vice versa.
Next, we decide to update how the turns are chosen, so we create a new class, NewTruthAndDare. It consists of the following modifications:
-
we set
turnto somerandomValuepassed through the constructor.constructor(randomValue){ this.turn = randomValue; } -
Next, we define the
newplayGamefunction.newplayGame(playerOnename,playerTwoname) { if((this.turn % 2) == 0){ return `${playerOnename}'s turn` }else{ return `${playerTwoname}'s turn` } }We access
turnand check whether it is even. If it’s even it is player 1’s turn, else, it is player 2’s turn.
Finally, we make sure that the interface does not change for the players; meaning, they keep on calling playGame without knowing that the method to randomize turns has changed or that the function name has changed to newplayGame. For this purpose, we define the Adapter class.
class Adapter {
constructor(randomValue) {
const newGame = new NewTruthAndDare(randomValue)
this.playGame = function(playerOnename,playerTwoname) {
return newGame.newplayGame(playerOnename,playerTwoname)
};
}
}
-
We create an object
newGameof the classNewTruthAndDare. -
Next, we define the
playGamefunction in it. In the definition, we call thenewGame.newplayGamefunction.
So now the players can keep on calling the playGame function as it is, but on the backend, the newplayGame function will execute instead.
const obj = new Adapter(6)
obj.playGame("Ross","Chandler") //`obj.playGame` will execute `newplayGame`
Let’s discuss the bridge pattern in the next lesson.