/** Cosine similarity in [-1, 1]; 0 when either vector is empty or zero or the lengths differ. */ export function cosineSimilarity(left: readonly number[], right: readonly number[]): number { if (left.length === 0 || left.length !== right.length) return 0; let dot = 0; let leftNorm = 0; let rightNorm = 0; for (let index = 0; index < left.length; index += 1) { const a = left[index]!; const b = right[index]!; dot += a * b; leftNorm += a * a; rightNorm += b * b; } return leftNorm === 0 || rightNorm === 0 ? 0 : dot / Math.sqrt(leftNorm * rightNorm); }