Created
February 14, 2021 17:09
-
-
Save theKAKAN/b40bf54144a6eb90313ad00681e3fbcc to your computer and use it in GitHub Desktop.
Convert degrees or angles to cardinal direction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getDirection( angle ){ | |
// We divide it into 16 sections | |
let directions = ["N","NNE","NE","ENE","E", | |
"ESE", "SE", "SSE","S", | |
"SSW","SW","WSW","W", | |
"WNW","NW","NNW" ]; | |
// This means, every 360 / 16 degree, there's a section change | |
// So, in our case, every 22.5 degree, there's a section change | |
// In order to get the correct section, we just need to divide | |
let section = parseInt( angle/22.5 + 0.5 ); | |
// If our result comes to be x.6, which should normally be rounded off to | |
// int(x) + 1, but parseInt doesn't care about it | |
// Hence, we are adding 0.5 to it | |
// Now we know the section, just need to make sure it's under 16 | |
section = section % 16; | |
// Now we can return it | |
return directions[ section ]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent work, and it saved me a bit of time.
I'm using TypeScript, and here's what I did with the code:
Everything appears to be working, so I'm assuming the
Math.floor()
didn't break anything? As an aside, TypeScript didn't like theparseInt()
.