blob: 2f8b0f0723e824a0a18832b9bb32c102ec539cc5 [file] [log] [blame]
module.exports = {
dotProduct: dotProduct,
norm: norm,
cossim: cossim
};
/*
* Computes the dot product of these two objects.
*/
function dotProduct(a, b) {
var sum = 0.0;
for (var key in a) {
if (a.hasOwnProperty(key) && b.hasOwnProperty(key)) {
sum += a[key] * b[key];
}
}
return sum;
}
/*
* Computes the norm of the given object.
*/
function norm(a) {
return Math.sqrt(dotProduct(a, a));
}
/*
* Computes the cosine similarity of these two objects.
*/
function cossim(a, b) {
var cs = dotProduct(a, b);
if (cs !== 0) { // This check prevents dividing by a 0 norm.
cs /= norm(a) * norm(b);
}
return cs;
}