Browse Source

Move math to a separate module

Kirk Trombley 3 years ago
parent
commit
520e23f61d
1 changed files with 16 additions and 0 deletions
  1. 16 0
      math.js

+ 16 - 0
math.js

@@ -0,0 +1,16 @@
+// Vector Math
+const vectorDot = (u, v) => u.map((x, i) => x * v[i]).reduce((x, y) => x + y);
+const vectorSqMag = v => vectorDot(v, v);
+const vectorMag = v => Math.sqrt(vectorSqMag(v));
+const vectorSqDist = (u, v) => vectorSqMag(u.map((x, i) => x - v[i]));
+const vectorDist = (u, v) => Math.sqrt(vectorSqDist(u, v));
+const vectorNorm = v => { const n = vectorMag(v); return [ n, v.map(c => c / n) ]; };
+
+// Angle Math
+const angleDiff = (a, b) => { const raw = Math.abs(a - b); return raw < 180 ? raw : (360 - raw); };
+const rad2deg = 180 / Math.PI;
+
+// Arg Compare
+const argComp = comp => ra => ra.map((x, i) => [x, i]).reduce((a, b) => comp(a[0], b[0]) > 0 ? b : a)[1];
+const argMin = argComp((a, b) => a - b);
+const argMax = argComp((a, b) => b - a);