feat(utils): compute cosine similarity, remove package

This commit is contained in:
ItzCrazyKns
2025-12-05 21:28:15 +05:30
parent 2c61f47088
commit a548fd694a
2 changed files with 18 additions and 4 deletions

View File

@@ -1,7 +1,22 @@
import cosineSimilarity from 'compute-cosine-similarity';
const computeSimilarity = (x: number[], y: number[]): number => {
return cosineSimilarity(x, y) as number;
if (x.length !== y.length)
throw new Error('Vectors must be of the same length');
let dotProduct = 0;
let normA = 0;
let normB = 0;
for (let i = 0; i < x.length; i++) {
dotProduct += x[i] * y[i];
normA += x[i] * x[i];
normB += y[i] * y[i];
}
if (normA === 0 || normB === 0) {
return 0;
}
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
};
export default computeSimilarity;