DEV Community

Cover image for How would you refactor this code? (tennis-3-modern)
Lars Grammel for P42

Posted on • Edited on

3

How would you refactor this code? (tennis-3-modern)

export class TennisGame {
  constructor(p1N, p2N) {
    this.p2 = 0;
    this.p1 = 0;

    this.p1N = p1N;
    this.p2N = p2N;
  }

  getScore() {
    let s;
    if (this.p1 < 4 && this.p2 < 4 && this.p1 + this.p2 < 6) {
      const p = ["Love", "Fifteen", "Thirty", "Forty"];
      s = p[this.p1];
      return this.p1 == this.p2 ? `${s}-All` : `${s}-${p[this.p2]}`;
    } else {
      if (this.p1 == this.p2) return "Deuce";
      s = this.p1 > this.p2 ? this.p1N : this.p2N;
      return (this.p1 - this.p2) * (this.p1 - this.p2) == 1
        ? `Advantage ${s}`
        : `Win for ${s}`;
    }
  }

  wonPoint(playerName) {
    if (playerName == "player1") this.p1 += 1;
    else this.p2 += 1;
  }
}

Enter fullscreen mode Exit fullscreen mode

I've created a modern version of the Tennis-3 refactoring kata. The class calculates the tennis score for a game. You can find the full code including a test suite on GitHub.

How would you refactor it?

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay