Last active
February 29, 2024 02:14
-
-
Save x1unix/d74e537c90dc254a51857927c816ed2d to your computer and use it in GitHub Desktop.
vec.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { log, assert } = console | |
const { abs, max, sqrt } = Math | |
const dbg = (v) => console.log(typeof v, v) | |
const pow2 = v => v * v | |
const sum = (a,b) => a + b | |
const sub = (a,b) => a - b | |
const mul = (a,b) => a * b | |
const range = (length, fn) => Array.from({length}, (_, i) => fn(i)) | |
const vecCellReduce = (i, vecs, fn) => range(vecs.length, (j) => vecs[j][i]).reduce(fn) | |
const vsumn = (n, ...vecs) => range(n, (i) => vecCellReduce(i, vecs, sum)) | |
const vsubn = (n, ...vecs) => range(n, (i) => vecCellReduce(i, vecs, sub)) | |
const vmuln = (n, ...vecs) => range(n, (i) => vecCellReduce(i, vecs, mul)) | |
// vectors sum | |
const vsum = (...vecs) => { | |
const n = max(...vecs.map(v => v.length)) | |
return vsumn(n, ...vecs) | |
} | |
// vectors substraction | |
const vsub = (...vecs) => { | |
const n = max(...vecs.map(v => v.length)) | |
return vsubn(n, ...vecs) | |
} | |
// vector multiplication, aka Hadamard product. | |
const vmul = (...vecs) => { | |
const n = max(...vecs.map(v => v.length)) | |
return vmuln(n, ...vecs) | |
} | |
// Scale a vector evenly, preserving a direction. | |
const vscale = (vec, n) => vec.map(v => v * n) | |
// vector distance from origin. | |
const vlen = (vec) => sqrt(vec.map(pow2).reduce(sum)) | |
// distance between vectors. | |
const vdist = (a, b) => vlen(vsub(a, b)) | |
//const vdist = (a, b) => vlen(a) + vlen(b) | |
// normalize a vector and return a unit vector with the same direction but length of 1. | |
const vnorm = (v) => { | |
const len = vlen(v) | |
return v.map(elem => elem / len) | |
} | |
// Computes a dot (scalar) product of vectors | |
const vdot = (a, b) => vmul(a, b).reduce(sum) | |
clear() | |
// dbg( | |
// vsub([10,9], [5,6]) | |
// ) | |
// dbg(vdist([3, 4], [0, 0])) // 5 | |
// dbg(vdist([4, -5], [-4, 5])) // 12.806 | |
// dbg(vlen([3, 4, 12])) // 13 | |
// Normalized vectors | |
// dbg(vnorm([3, 4])) // 0.6, 0.8 | |
// dbg(vnorm([-1, -1])) // -0.707, -0.707 | |
// dbg(vnorm([0.5, 0.5])) // 0.707, 0.707 | |
// Hadamard product | |
// dbg(vscale([1,2,3], 5)) | |
// dbg(vmul([5, 6], [5, 5])) | |
// dbg(vmul([1,2,3], [1, -1, 1])) | |
// Dot product | |
dbg(vdot([1,2], [1,3])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment