Angle difference between two bearings: Difference between revisions

Content added Content deleted
(→‎JS ES6: Tidied)
Line 1,640: Line 1,640:


<lang JavaScript>(() => {
<lang JavaScript>(() => {
"use strict";

// ------ ANGLE DIFFERENCE BETWEEN TWO BEARINGS ------


// bearingDelta :: Radians -> Radians -> Radians
// bearingDelta :: Radians -> Radians -> Radians
const bearingDelta = (ar, br) => {
const bearingDelta = a =>
// The difference between two bearings: a and b.
const [ax, ay] = [sin(ar), cos(ar)], [bx, by] = [sin(br), cos(br)],
b => {
const [ax, ay] = [sin(a), cos(a)];
const [bx, by] = [sin(b), cos(b)];


// Cross-product > 0 ?
// Cross-product above zero ?
sign = ((ay * bx) - (by * ax)) > 0 ? +1 : -1;
const sign = ((ay * bx) - (by * ax)) > 0 ? (
+1
) : -1;


// Sign * dot-product
// Sign * dot-product.
return sign * acos((ax * bx) + (ay * by));
return sign * acos((ax * bx) + (ay * by));
};
};


// Pi, sin, cos, acos :: Function
const [Pi, sin, cos, acos] = ['PI', 'sin', 'cos', 'acos']
.map(k => Math[k]),
degRad = x => Pi * x / 180.0,
radDeg = x => 180.0 * x / Pi;


// ---------------------- TEST -----------------------

// main :: IO ()
// TEST ------------------------------------------------------------------
const main = () => [

// justifyRight :: Int -> Char -> Text -> Text
const justifyRight = (n, cFiller, strText) =>
n > strText.length ? (
(cFiller.repeat(n) + strText)
.slice(-n)
) : strText;

// showMap :: Degrees -> Degrees -> String
const showMap = (da, db) =>
justifyRight(6, ' ', `${da}° +`) +
justifyRight(11, ' ', ` ${db}° -> `) +
justifyRight(7, ' ', `${(radDeg(bearingDelta(degRad(da), degRad(db))))
.toPrecision(4)}°`);

return [
[20, 45],
[20, 45],
[-45, 45],
[-45, 45],
Line 1,683: Line 1,671:
[-45, 145]
[-45, 145]
].map(xy => showMap(...xy))
].map(xy => showMap(...xy))
.join('\n');
.join("\n");


// ------------------- FORMATTING --------------------

// showMap :: Degrees -> Degrees -> String
const showMap = (da, db) => {
const
delta = degreesFromRadians(
bearingDelta(
radiansFromDegrees(da)
)(
radiansFromDegrees(db)
)
)
.toPrecision(4),
theta = `${da}° +`.padStart(6, " "),
theta1 = ` ${db}° -> `.padStart(11, " "),
diff = `${delta}°`.padStart(7, " ");

return `${theta}${theta1}${diff}`;
};

// --------------------- GENERIC ---------------------

// radiansFromDegrees :: Float -> Float
const radiansFromDegrees = n =>
Pi * n / 180.0;

// degreesFromRadians :: Float -> Float
const degreesFromRadians = x =>
180.0 * x / Pi;

// Abbreviations for trigonometric methods and
// properties of the standard Math library.
const [
Pi, sin, cos, acos
] = ["PI", "sin", "cos", "acos"]
.map(k => Math[k]);

// MAIN ---
return main();
})();</lang>
})();</lang>
{{Out}}
{{Out}}