DEV Community

Cover image for JavaScript Katas: Calculate total amount of points
miku86
miku86

Posted on

JavaScript Katas: Calculate total amount of points

Intro 🌐

I take interesting katas of all levels and explain how to solve them.

Problem solving is an important skill, for your career and your life in general.

You'd better learn to solve problems!


Source

I take the ideas for the katas from different sources and re-write them.

Today's source: Codewars


Understanding the Exercise ❗

First, we need to understand the exercise!

This is a crucial part of (software) engineering.

Go over the exercise explanation again until you understand it 100%.

Do NOT try to save time here.

My method to do this:

  1. Input: What do I put in?
  2. Output: What do I want to get out?

Today's exercise

Write a function calculateAmountOfPoints, that accepts one parameter: games, a valid array of strings, e.g. ["3:1", "2:2"].

Points:

  • x > y: 3 points
  • x = y: 1 point
  • x < y: 0 point

The function should return a number. The number is the sum of the point(s) of every single game.


Input: an array of strings.

Output: a number.


Thinking about the Solution 💭

I think I understand the exercise (= what I put into the function and what I want to get out of it).

Now, I need the specific steps to get from input to output.

I try to do this in small baby steps.

  1. loop over every element of the games array
  2. calculate the specific score of this element
  3. return the sum of every single element (a number)

Example:

  • Input: ["3:1", "2:2"]
  • Iteration 1: "3:1" // x > y => 3 points
  • Iteration 2: "2:2" // x = y => 1 point
  • Output: 4 // return the sum (3 + 1) as a number

Implementation (for of-loop) ⛑

function calculateAmountOfPoints(games) {
  // counter for total points
  let totalPoints = 0;

  for (const game of games) {
    // split the game score for both teams and assign it to two variables
    const [scoreA, scoreB] = game.split(":");

    // calculate the points for this game with a ternary operator
    const points = scoreA > scoreB ? 3 : scoreA === scoreB ? 1 : 0;

    // add the points for this specific game to the total points
    totalPoints += points;
  }

  return totalPoints;
}
Enter fullscreen mode Exit fullscreen mode

Result

console.log(calculateAmountOfPoints(["3:1", "2:2"]));
// 4

console.log(calculateAmountOfPoints(["1:0", "2:0", "3:0", "4:0", "2:1"]));
// 15
Enter fullscreen mode Exit fullscreen mode

Implementation (functional) ⛑

function calculateAmountOfPoints(games) {
  return (
    games
      // split the game score into two separate values
      .map((game) => game.split(":"))

      // calculate the points for this game with a ternary operator
      .map((score) => (score[0] > score[1] ? 3 : score[0] === score[1] ? 1 : 0))

      // calculate the sum of all games
      .reduce((acc, cur) => acc + cur, 0)
  );
}
Enter fullscreen mode Exit fullscreen mode

Result

console.log(calculateAmountOfPoints(["3:1", "2:2"]));
// 4

console.log(calculateAmountOfPoints(["1:0", "2:0", "3:0", "4:0", "2:1"]));
// 15
Enter fullscreen mode Exit fullscreen mode

Playground ⚽

You can play around with the code here


Next Part ➡️

Great work, mate!

Next time, we'll solve the next kata. Stay tuned!

If I should solve a specific kata, shoot me a message here.

If you want to read my latest stuff, get in touch with me!


Further Reading 📖


Questions ❔

  • Do you like to solve katas?
  • Which implementation do you like more? Why?
  • Any alternative solution?

Top comments (4)

Collapse
 
sh786 profile image
Sam Hamburger

Is there a benefit to memoizing the point addition of a specific game's score to avoid splitting, and comparing values, when we have already done so for the duplicate score?

I solved as shown below:

const calculateAmountOfPoints = games => {
  const seenScores = {};
  let total = 0;
  games.forEach(game => {
    if (seenScores[game]) {
      total += seenScores[game];
    } else {
      const [x, y] = game.split(":");
      let thisScore = 0;
      if (x > y) thisScore = 3;
      if (x === y) thisScore = 1;
      total += thisScore;
      seenScores[game] = thisScore;
    }
  });
  return total;
};
Collapse
 
miku86 profile image
miku86

Hey Sam,

great question, thanks!

If the performance of your application is a bottleneck, you could get some benefits through the memoizing.

There are probably already some optimizations going on under the hood of the JS engine, so I don't know about the magnitude of this manual memoizing.

If you know more about this topic or this specific case, please let us know.

Greetings
Michael

Collapse
 
timhuang profile image
Timothy Huang

Amazing!! Thanks for sharing!

Collapse
 
miku86 profile image
miku86

Hi Timothy,

glad you like it!