Challenge 7 suggestion

It wouldn’t be nice if we have to make a compass function that we give the wind direction in degrees and receive the nearest direction position as “NNE”, “NE” or “ENE” for example.

1 Like

I did that challenge 7 suggestion at that time. But after all these days I would probably do it differently.

// function compass receives direction in degrees returns cardinal position

const compass = function(degree){

  const cardinalPrecision = ["N", "Nbe", "NNE", "NEbN", "NE", "NEbE", "ENE", "NbN", "E", "EbS", "ESE", "SEbE", "SE", "SEbS", "SSE", "Sbe", "S", "SbW", "SSW", "SWbS", "SW", "SWbW", "WSW", "WbS", "W", "WbN", "WNW", "NWbW", "NNW", "NWbW", "NNW", "NbW", "N"];

  const pace = 360 / (cardinalPrecision.length - 1); // degrees between cardinals

    for(let i = 0 ; i < cardinalPrecision.length ; i++){

      if(degree < ( i * pace)){ // search greatest cardinal

       return ((i * pace) - degree) < (degree - ((i - 1) * pace)) ? //Which is the

        cardinalPrecision[i] : cardinalPrecision[i - 1]; // nearest cardinal

      }

    }

   return degree == 360 ? cardinalPrecision[0] : false; // if any result was found

}

console.log(compass(160));

console.log(compass(200));

console.log(compass(260));

console.log(compass(215));

console.log(compass(279));

console.log(compass(0));

console.log(compass(360));

console.log(compass(20));
1 Like

How i choose to do it would depend upon how they provide it, but would likely use fall-through processing.

1 Like