Created
October 13, 2025 01:31
-
-
Save paceaux/2909de961036d0c38119ac98606b7732 to your computer and use it in GitHub Desktop.
Vector Functions
This file contains hidden or 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
/* | |
* @description Gets the euclidian distance of two vectors | |
* @param {Array.<number>} v1 - a vector of numbers | |
* @param {Array.<number>} v2 - a vector of numbers | |
* @returns {number} A float | |
*/ | |
function euclidian(v1, v2) { | |
const squares = v1.map((el, idx) => { | |
const subtr = el - v2[idx]; | |
return Math.pow(subtr, 2) | |
}) | |
return Math.sqrt(squares.reduce((acc, curr) => acc + curr, 0)); | |
} | |
/* | |
* Normalizes a vector | |
* @param {Array.<number>} vector - a list of numbers | |
* @returns {Array.<number>} a list of floats | |
*/ | |
function normalize(vector) { | |
const squares = vector.map(el => Math.pow(el, 2)) | |
const sum = squares.reduce((acc, cur) => acc + cur, 0) | |
const sqrRoot = Math.sqrt(sum) | |
const normies = vector.map(el => el / sqrRoot) | |
return normies | |
} | |
/* | |
* @description Gets the pNorm of a vector | |
* @param {Array.<number>} vector - a vector of numbers | |
* @param {number} int - an integer to indicate the normalization | |
* @returns {number} A float | |
*/ | |
function pNorm(vector, int) { | |
const exps = vector.map((el) => Math.pow(el, int)); | |
const sums = exps.reduce((acc, cur) => acc + cur, 0); | |
return Math.pow(sums, 1/int); | |
} | |
/* | |
* @description Gets the dot product of two vectors | |
* @param {Array.<number>} v1 - a vector of numbers | |
* @param {Array.<number>} v2 - a vector of numbers | |
* @returns {Array.<number>} An array of floats | |
*/ | |
function dotProduct(v1, v2) { | |
return v1 | |
.map((el, idx) => el * v2[idx]) | |
.reduce((acc, cur) => acc + cur, 0); | |
} | |
/* | |
* @description Gets the cosine similarity of two vectors | |
* @param {Array.<number>} v1 - a vector of numbers | |
* @param {Array.<number>} v2 - a vector of numbers | |
* @returns {number} | |
*/ | |
function cosineSimilarity(v1, v2) { | |
const p1 = pNorm(v1); | |
const p2 = pNorm(v2); | |
const prod = dotProd(v1, v2); | |
return (prod / (p1 * p2)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment