← All Exercises
Rank Documents with Term Frequency and IDF
advancedjavascript
Background
Ranking by raw count over-rewards common words. IDF weighting is the smallest change that makes search results useful before adopting a full BM25 engine.
Problem
Score documents for a multi-term query using summed term frequency weighted by inverse document frequency, then return the ranked ids.
Input
JSON object: { documents: [{ id, text }], query: string }Output
JSON array of { id, score } sorted by score desc, then idSample tests
Sample 1
Input: {"documents":[{"id":"d1","text":"cache cache timeout"},{"id":"d2","text":"cache invalidation"},{"id":"d3","text":"timeout policy"}],"query":"cache timeout"}Expected: [{"id":"d1","score":2.7489},{"id":"d2","score":0.9163},{"id":"d3","score":0.9163}]Sample 2
Input: {"documents":[{"id":"d4","text":"unrelated content"}],"query":"cache"}Expected: [{"id":"d4","score":0}]Your solution
Learning objective
Implement weighted term ranking that explains why a document wins.