Created
November 25, 2017 19:37
-
-
Save lunaroyster/22cf3c186ef5c2ef07b3394446199252 to your computer and use it in GitHub Desktop.
A minimalist (amateur) implementation of 'Vector', along with cosineSimilarity
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
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