Golf Code - Is this a better application?

Golf Code - Is this a better application?
0.0 0

#1

Hi there!
Would this code be considered to be a more elegant execution of this mission, or is this way of writing redundant?
What would be the most optimal way to write that kind of code?
Thanks in advance.

My application of the code

function golfScore(par, strokes) {
  // Only change code below this line
  var conditions = {
    "Hole-in-one!": (strokes == 1),
    "Eagle": (strokes <= par - 2),
    "Birdie": (strokes == par - 1),
    "Par": (strokes == par),
    "Bogey": (strokes == (par + 1)),
    "Double Bogey": (strokes == (par + 2)),
    "Go Home!": (strokes >= (par + 3))
  };
  
  for (var key in conditions) {
    if (conditions[key]) {
      return key;
    }
  }
  // Only change code above this line
}

// Change these values to test
golfScore(4, 1);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0.

Link to the challenge:


#2

I think you have a good approach to this problem. Based on where this challenge is located in the FCC curriculum, they were probably looking for a more if/else if chaining type of code, though.

When you say most optimal way, there is not necessarily a single way things are done, as there are time and space tradeoffs (big-O notation). Looking something up in an object is constant time, but if you had if-else statements, you wouldn’t need an object (this particular object doesn’t grow based on the inputs, so it’d still be constant space). Anyway, all this to say the tradeoffs are negligible for this problem, but readability-wise I think this one is easier to see/understand than the if/elses you would have otherwise.