Golf Code 1 line solution

Tell us what’s happening:

Your code so far


var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
  // Only change code below this line
  if (strokes == 1){
    return names[0];
  } else if (strokes <= par -2){
    return names[1];
  } else if (strokes == par - 1){
    return names[2];
  } else if (strokes == par) {
    return names[3];
  } else if (strokes == par + 1) {
    return names[4];
  } else if (strokes == par + 2) {
    return names[5];
  }
  
  return names[6];
  // Only change code above this line
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/golf-code/

I was just curious what the one line of code solution is for this. like function golfScores(par, strokes) {
return names[ math goes here ] ; }

This challenge isn’t a good candidate for a one line solution. Remember that shorter code doesn’t always mean a better solution.

1 Like
var golfScore = (par, strokes) => {
      return strokes === 1
      	? names[0]
      	: strokes >= par + 3
      		? names[6]
      		: names[[-2, -1, 0, 1, 2].findIndex((val) => strokes <= par + val) + 1]
};

This is about as close as I could get without using eval.

2 Likes

@kerafyrm02 Nice solution! You could remove the nested ternary by comparing with Infinity:

Spoiler
var golfScore = (par, strokes) => {
  return strokes === 1
    ? names[0]
    : names[[-2, -1, 0, 1, 2, Infinity].findIndex((val) => strokes <= par + val) + 1]
};

Code-golf version:

(p,s)=>s==1?names[0]:names[[-2,-1,0,1,2,1/0].findIndex(n=>s<=p+n)+1]

But as @ArielLeslie says:

Code golf is fun and all, but usually doesn’t result in very elegant or readable code!

1 Like

Slick., Infinity was a nice addition.