Frame · dsa / ai-algorithms / 05-reciprocal-rank-fusion.jsJavaScript
Reciprocal Rank Fusion for Hybrid Search
Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.
Same file as in the repo · ~20s timeout
From file header (JSDoc)
Reciprocal Rank Fusion for Hybrid Search
Problem: Hybrid search runs several retrievers (for example BM25 and a
vector index) whose scores are on incompatible scales. Reciprocal Rank
Fusion (RRF) merges ranked lists using only positions:
RRF(d) = sum over lists L containing d of weight(L) / (k + rank_L(d))
where rank is 1-based and k defaults to 60. Given an array of ranked id
lists (and optional per-list weights), return `{ id, score }` objects sorted
by score descending; ties are broken by the id's best (smallest) rank in any
list, then by id string order. Duplicate ids within one list count only at
their first position.
Constraints:
- 1 <= lists.length <= 10, each list length <= 1000
Example:
lists = [["a","b","c"], ["b","c","d"]], k = 60
-> b: 1/62 + 1/61, c: 1/63 + 1/62, a: 1/61, d: 1/63 => [b, c, a, d]
Approach: Accumulate scores in a map in one pass over every list, tracking
each id's best rank for tie-breaking, then sort. Time O(T + U log U) with T
total entries and U unique ids, space O(U).
@param {string[][]} lists
@param {{ k?: number, weights?: number[] }} [opts]
@returns {{ id: string, score: number }[]}