Skip to content

Instantly share code, notes, and snippets.

@brugos
Created September 25, 2025 11:56
Show Gist options
  • Save brugos/b37cefadd53a6bf6dbbef9aaca87eb0e to your computer and use it in GitHub Desktop.
Save brugos/b37cefadd53a6bf6dbbef9aaca87eb0e to your computer and use it in GitHub Desktop.
cosine similarity
function cosineSimilarity(a: number[], b: number[]): number {
const dot = a.reduce((s, ai, i) => s + ai * (b[i] ?? 0), 0);
const na = Math.sqrt(a.reduce((s, ai) => s + ai * ai, 0));
const nb = Math.sqrt(b.reduce((s, bi) => s + bi * bi, 0));
return dot / (na * nb);
}
type Vec = { id: string; vector: number[] };
const embeddings: Vec[] = [
{ id: "1", vector: [0.1, 0.2, 0.3] },
{ id: "2", vector: [0.2, 0.1, 0.4] },
{ id: "3", vector: [0.9, 0.8, 0.1] },
];
const query = [0.2, 0.2, 0.3];
const ranked = embeddings
.map((e) => ({ ...e, score: cosineSimilarity(query, e.vector) }))
.sort((a, b) => b.score - a.score);
console.log("ranked by cosine similarity:", ranked);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment