Home > katas > Total amount of points (8kyu) [JavaScript]
Total amount of points (8kyu) [JavaScript]
Chek kata on Codewars
Description:
Our football team finished the championship. The result of each match look 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
Notes:
there are 10 matches in the championship
0 <= x <= 4
0 <= y <= 4
Loop
function points(games) {
let answer = 0
for(const score of games) {
const arr = score.split(":")
if(Number(arr[0]) > Number(arr[1])) {
answer += 3
} else if (Number(arr[0]) == Number(arr[1])) {
answer += 1
}
}
return answer
}
Reduce
function points(games) {
return games.reduce((acc, cur) => acc + (cur[0] > cur[2] ? 3 : cur[0] == cur[2] ? 1 : 0), 0)
}
function points(games) {
return games.reduce( (acc, [x, _, y]) => acc + (x > y ? 3 : x == y), 0)
}
Map & Reduce
function points(games) {
return games
.map(str => str.split(":").map(Number))
.map(([x,y]) => x > y ? 3 : x == y ? 1 : 0)
.reduce((acc, cur) => acc + cur, 0)
}