Codewars Total amount of points – Easy Solution Javascript (8 kyu)

This is the solution for the Codewars Total amount of points question in Javascript with a simple & easy to understand code and explanation.

Task:

Our football team finished the championship. The result of each match looks like “x:y”. Results of all matches are recorded in the collection.

For example: ["3:1", "2:2", "0:1", ...]

Write a function that takes such collection and counts the points of our team in the championship. Rules for counting points for each match:

  • if x>y – 3 points
  • if x<y – 0 point
  • if x=y – 1 point

Here’s the link to the kata – Total amount of points

Solution to Total amount of points Question:

The simple solution to the ‘Total amount of points’ question is to first loop through the strings given in the games array, if the 0th index of games[i] > 2nd index of games[i] we have to add 3 to the score, else if they are equal we need to add 1 to the score. Finally, return the score value.

function points(games) {
  let sum=0;
  for (let i=0; i<games.length; ++i)
  {
    if (games[i][0]>games[i][2])
      sum+=3;
    if (games[i][0]==games[i][2])
      sum+=1;
  }
  return sum;
}
//solution style 1 - easy to read and understand

function points(games) {
  let result = [];
  let score = 0;
  games.forEach(x => {
    result = x.split(":");
    if(parseInt(result[0])>parseInt(result[1]))
      score += 3;
    else if(result[0]==result[1])
      score += 1;
    else
      score += 0;
  })
  return score;
}
//solution style 2 - single line

const points=games=>games.reduce((output,current)=>{
    
return output += current[0]>current[2] ? 3 : current[0] === current[2] ? 1 : 0;  },0)

Leave a Comment