Skip to content

Instantly share code, notes, and snippets.

@lunaroyster
Created November 25, 2017 19:37
Show Gist options
  • Save lunaroyster/22cf3c186ef5c2ef07b3394446199252 to your computer and use it in GitHub Desktop.
Save lunaroyster/22cf3c186ef5c2ef07b3394446199252 to your computer and use it in GitHub Desktop.
A minimalist (amateur) implementation of 'Vector', along with cosineSimilarity
class Vector {
constructor(VectorArray) {
//TODO: Check things?
this._values = VectorArray;
}
toArray() {
return this._values;
}
get length() {
return this._values.length;
}
get magnitude() {
let squareSum = 0;
for(let i of this._values) {
squareSum+=i**2;
}
return squareSum**0.5
}
static dotProduct(a, b) {
if(a.length!=b.length) throw Error("Bad vector");
let sum = 0;
for(let i = 0; i<a.length; i++) {
sum+=(a._values[i]*b._values[i]);
}
return sum;
}
static cosineSimilarity(a, b) {
return Vector.dotProduct(a, b)/(a.magnitude * b.magnitude);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment