Skip to content

Instantly share code, notes, and snippets.

@theKAKAN
Created February 14, 2021 17:09
Show Gist options
  • Save theKAKAN/b40bf54144a6eb90313ad00681e3fbcc to your computer and use it in GitHub Desktop.
Save theKAKAN/b40bf54144a6eb90313ad00681e3fbcc to your computer and use it in GitHub Desktop.
Convert degrees or angles to cardinal direction
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 ];
}
@OctaneInteractive
Copy link

Excellent work, and it saved me a bit of time.

I'm using TypeScript, and here's what I did with the code:

export const getDirection = ( angle: number ): string => {
	let directions: string[] = [
		"N", "NNE", "NE", "ENE",
		"E", "ESE", "SE", "SSE",
		"S", "SSW", "SW", "WSW",
		"W", "WNW", "NW", "NNW"
	]

	const section: number = Math.floor(angle / 22.5 + 0.5)

	return directions[ section % 16 ]
}

Everything appears to be working, so I'm assuming the Math.floor() didn't break anything? As an aside, TypeScript didn't like the parseInt().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment