Skip to content

Instantly share code, notes, and snippets.

@mhansen
Created May 7, 2018 11:36
Show Gist options
  • Save mhansen/85cc62a7bfcf7ba41293e352a068a882 to your computer and use it in GitHub Desktop.
Save mhansen/85cc62a7bfcf7ba41293e352a068a882 to your computer and use it in GitHub Desktop.
Calculate whether a difference in angle is clockwise or anticlockwise.
function isClockwise(from, to) {
let diff = normalize(from) - normalize(to);
return normalize(diff) > 180;
}
// Returns angle normalized to between [0, 360).
function normalize(angle) {
while (angle < 0) {
angle += 360;
}
while (angle >= 360) {
angle -= 360;
}
return angle;
}
let tests = [
// Clockwise
[0, 90, true],
[90, 180, true],
[180, 270, true],
[270, 0, true],
// Counter-clockwise
[0, 270, false],
[270, 180, false],
[180, 90, false],
[90, 0, false],
// 179 degree angles
[179, 0, false],
[181, 0, true],
// Arbitrary ones
[180, 0, false], // arbitrary
[0, 0, false], // arbitrary
// Input invalid
[720, 0, false],
[0, 720, false],
];
let failures = tests.reduce(function(failedTests, t) {
let actual = isClockwise(t[0], t[1]);
let expected = t[2];
if (actual != expected) {
console.log("Failed: isClockWise("+t[0]+", "+t[1]+")="+actual+", wanted="+expected);
return failedTests + 1;
}
return failedTests;
}, 0);
if (failures == 0) {
console.log("OK");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment