Still learning JS and I made the following function to convert degrees into cardinal directions respectively. My first iteration of the code was over 50 lines and I was able to get it down to 13 using a for loop.
Is there a way to optimize or simplify the code down even more? Is my logic and implementation ideal?
https://codepen.io/bbbenji/pen/JjPGNmY
function setCardinalDirection() {
value = document.querySelector('#orientation').value // Get current value from range input
document.querySelector(".degrees").textContent = value // Inject current input value into label
direction = document.querySelector(".direction") // Define intercardinal direction display element
degrees = 22.5 // Define range between two intercardinal directions
cardinal = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N"]
for ( i = cardinal.length; i >= 0; i-- ) { // Iterate through cardinal array backwards
if ( value < degrees/2 + degrees * i ) {
cardinalOut = cardinal[i]
}
}
direction.textContent = cardinalOut // Inject current cardinal value into label
}
document.querySelector("#orientation").addEventListener('input', function(event) {
setCardinalDirection()
})
window.addEventListener("load", function(){
setCardinalDirection()
})
<form>
<label for ="orientation">
Orientation: <strong><span class="degrees"></span>° (<span class="direction"></span>)</strong>
</label>
<br />
<input id="orientation" type="range" min="0" max="360" step="1" value="145">
</form>