Skip to content

Instantly share code, notes, and snippets.

@rjchow
Created September 21, 2018 16:14
Show Gist options
  • Save rjchow/936c44613de17d31c86f5adf59e816dd to your computer and use it in GitHub Desktop.
Save rjchow/936c44613de17d31c86f5adf59e816dd to your computer and use it in GitHub Desktop.
refactoring-kata
class Player {
constructor(playerName) {
this.name = playerName;
this.score = 0;
}
incrementPoints(increment = 1) {
this.score += increment;
}
getPoints() {
return this.score;
}
}
class TennisGame1 {
constructor(player1Name, player2Name) {
this.player1 = new Player(player1Name);
this.player2 = new Player(player2Name);
}
wonPoint(playerName) {
if (playerName === this.player1.name) this.player1.incrementPoints();
if (playerName === this.player2.name) this.player2.incrementPoints();
}
playerHasGreaterThan4Points() {
return this.player1.getPoints() >= 4 || this.player2.getPoints() >= 4;
}
isPlayerAtAdvantage() {
return (
this.playerHasGreaterThan4Points() &&
Math.abs(this.player1.getPoints() - this.player2.getPoints()) === 1
);
}
getLeadingPlayer() {
return this.player1.getPoints() > this.player2.getPoints()
? this.player1.name
: this.player2.name;
}
playerHasWon() {
return (
this.playerHasGreaterThan4Points() &&
Math.abs(this.player1.getPoints() - this.player2.getPoints()) >= 2
);
}
isTieScore() {
return this.player1.getPoints() === this.player2.getPoints();
}
getScore() {
if (this.isTieScore()) return Reporter.reportTieScore(this.player1.getPoints());
if (this.isPlayerAtAdvantage()) return Reporter.reportAdvantage(this.getLeadingPlayer());
if (this.playerHasWon()) return Reporter.reportWin(this.getLeadingPlayer());
else {
return Reporter.reportOngoingScore(
this.player1.getPoints(),
this.player2.getPoints()
);
}
}
}
const pointsToLabelMapping = {
0: "Love",
1: "Fifteen",
2: "Thirty",
3: "Forty"
};
class Reporter {
static reportTieScore(score) {
switch (score) {
case 0:
case 1:
case 2:
return `${pointsToLabelMapping[score]}-All`;
default:
return "Deuce";
}
}
static reportAdvantage(playerName) {
return `Advantage ${playerName}`;
}
static reportWin(playerName) {
return `Win for ${playerName}`;
}
static reportOngoingScore(player1Score, player2Score) {
return [
pointsToLabelMapping[player1Score],
pointsToLabelMapping[player2Score]
].join("-");
}
}
if (typeof window === "undefined") {
module.exports = TennisGame1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment