DEV Community

Cesar Del rio
Cesar Del rio

Posted on • Edited on

#14 - Keypad Horror CodeWars Kata (7 kyu)

Instructions

Paul is an excellent coder and sits high on the CW leaderboard. He solves kata like a banshee but would also like to lead a normal life, with other activities. But he just can't stop solving all the kata!!

Given an array (x) you need to calculate the Paul Misery Score. The values are worth the following points:

kata = 5
Petes kata = 10
life = 0
eating = 1

The Misery Score is the total points gained from the array. Once you have the total, return as follows:

< 40 = 'Super happy!'
< 70 >= 40 = 'Happy!'
< 100 >= 70 = 'Sad!'

100 = 'Miserable!'


My solution:

function paul(x){
var map = x.reduce((acc, el)=> {
  acc[el] = (acc[el] || 0) + 1;
  return acc;
}, {});

  let r = 0;

  for(const s in map){
   if(s == 'kata') r+=(map[s]*5)
   if(s == 'Petes kata') r+=(map[s]*10)
   if(s == 'eating') r+=(map[s])
   if(s == 'life') r+=(map[s]*0)
  }

  return r<40 ? 'Super happy!' : r<70 ? 'Happy!' : r<100 ? 'Sad!' : 'Miserable!'

}
Enter fullscreen mode Exit fullscreen mode

Explanation

First I took the array of strings and I reduced it so I could get an object with every repetition of the element as the key and the element as the value.

For example:

['kata', 'Petes kata', 'eating', 'eating', 'life', 'kata']

Returns:

{'kata': 2, 'Petes kata': 1, 'eating': 2, 'life': 1}


After that I used a loop that iterated the object, and I used if so I could check the value, because remember that every value is worth different points so:

kata = 5
Petes kata = 10
life = 0
eating = 1

So I had to multiply the number of repetitions of that value by the number of points that it is worth, and then I just returned the "r" variable using ternary conditionals for the different results depending on the points

return r<40 ? 'Super happy!' : r<70 ? 'Happy!' : r<100 ? 'Sad!' : 'Miserable!'


Comment how would you solve this kata and why? πŸ‘‡πŸ€”

My Github
My twitter
Solve this Kata

Top comments (0)