Writing Golf Code cleaner than the basic code

Viewed 59

Solved this problem using the below method. But would any JavaScript developer who is experienced could write this in a cleaner way? I was thinking you can loop through the "names" array and make the code cleaner but no matter how much I try it doesn't make sense outside of this box. Any tips would be greatly appreciated! Just trying to challenge myself into the next phase...

var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
  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]
  } else if (strokes >= par + 3) {
    return names[6]
  }
}


3 Answers

You could check with direct values or by using the delta and return the found value or a default value.

function golfScore(par, strokes) {
    if (strokes === 1) return names[0];
    var delta = strokes - par;
    if (delta <= -2 ) return names[1];
    return names[delta + 3] || names[6];
}

var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
//                             -2          -1     0       1          2              3
var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"];
function golfScore(par, strokes) {
  if (strokes <= 1) { // special case
    return names[0]
  } 

  if (strokes >= par + 3) { // higher bound
    return names[6]
  }

  if(strokes - par - 2 + 1 < 1) { // lower bound - not handled :<
    return "No name for this one, boi"
  }

  // in between
  return strokes[strokes - par - 2 + 1]; 
  // TODO: Name magic numbers
}

Of course it depends if names will change.
If so, then I would make this code array-length dependant.
And of course, tests are needed.

Note: I've never played golf.

In the following solution function index is used to convert the delta to an index in the names array.

If the number of strokes is 1, then we pass an identifiable non-number (NaN), so a hole-in-one can be detected. Otherwise, we normalise values less than -2 or greater than 3.

let names = [ 'Hole-in-one!', 'Eagle!', 'Birdie!', 'Par', 'Bogey!', 'Double Bogey!', 'Go Home!']

const index = Δ => isNaN(Δ) 
  ? 0 
  : Δ <= -2 
    ? 1 
    : Δ >= 3 
      ? 6 
      : +Δ+3

const golfScore = (par, strokes) => names[index(strokes == 1 ? NaN : strokes-par)]

console.log(golfScore(3,3)) // 'Par'

Related