Find the new rotation value from the current rotation and the new value.
function normalizeCSSHeading(oldHeading, newHeading) {
"use strict";
// find the difference in degrees first
let oldH = oldHeading;
if (oldH < 0) {
oldH = 365 + (oldH % 365);
}
let newH = newHeading;
if (newH < 0) {
newH = 365 + (newH % 365);
}
let diff = newH % 365 - oldH % 365;
// find shortest path
if (diff < -180) {
diff = 365 - Math.abs(diff);
} else if (diff > 180) {
diff = diff - 365;
}
return oldHeading + diff;
}
// some jasmine tests
describe('normalizeCSSHeading', function() {
it ('should all work', function() {
expect(normalizeCSSHeading(0, 0)).toEqual(0);
expect(normalizeCSSHeading(0, 10)).toEqual(10);
expect(normalizeCSSHeading(376, 10)).toEqual(375);
expect(normalizeCSSHeading(-124, 310)).toEqual(-55);
expect(normalizeCSSHeading(-124, -90)).toEqual(-90);
expect(normalizeCSSHeading(1459, 6)).toEqual(1466); // 1459 % 365 = 364
expect(normalizeCSSHeading(-30, 200)).toEqual(-165);
expect(normalizeCSSHeading(439, -15)).toEqual(350); // 439 % 365 = 74
expect(normalizeCSSHeading(0, -95)).toEqual(-95);
});
});