typescriptintermediate

Cosine Similarity for Embeddings

Compute cosine similarity between embedding vectors for semantic search and recommendation systems.

typescript
function cosineSimilarity(a: number[], b: number[]): number {
  let dot = 0;
  let normA = 0;
  let normB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}

interface SearchResult {
  text: string;
  score: number;
}

export function findSimilar(
  query: number[],
  documents: { text: string; embedding: number[] }[],
  topK: number = 5,
): SearchResult[] {
  return documents
    .map((doc) => ({
      text: doc.text,
      score: cosineSimilarity(query, doc.embedding),
    }))
    .sort((a, b) => b.score - a.score)
    .slice(0, topK);
}

Use Cases

  • Semantic search over documents
  • Finding related content recommendations
  • Deduplication using embedding similarity

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.