Search Engine Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Search Engine runs in O(n log n) time and O(n) space, in JavaScript as in every other language.
- ✓Map<string, Map<number, number>> is the right container -- a plain object coerces every key to a string and reorders integer-like ones.
- ✓Reviewers reject arr.sort() with no comparator and reject {} as a term map. They want Map and Set, `??` rather than `||` when a term frequency can legitimately be 0, and true private #fields on the index class instead of an underscore convention.
- ✓The JavaScript trap: Array.prototype.sort with no comparator converts every element to a string and compares UTF-16 code units.
- ✓V8 caches a string's hash on the string object, so repeated Map lookups of the same token do not rehash -- token reuse is nearly free, novel tokens are not.
What Search Engine actually is
Search Engine in JavaScript: what you actually reach for
JavaScript implementation
const seg = new Intl.Segmenter("en", { granularity: "word" });
function tokens(text) {
const out = [];
for (const s of seg.segment(text.normalize("NFKC")))
if (s.isWordLike) out.push(s.segment.toLowerCase());
return out;
}
export class InvertedIndex {
#postings = new Map(); // term -> Map(docId -> tf)
#len = new Map();
add(docId, text) {
const t = tokens(text);
this.#len.set(docId, t.length);
for (const term of t) {
let m = this.#postings.get(term);
if (m === undefined) this.#postings.set(term, (m = new Map()));
m.set(docId, (m.get(docId) ?? 0) + 1);
}
}
search(query, k = 10) {
const N = this.#len.size, scores = new Map();
for (const term of tokens(query)) {
const m = this.#postings.get(term);
if (m === undefined) continue;
const idf = Math.log(1 + (N - m.size + 0.5) / (m.size + 0.5));
for (const [doc, tf] of m)
scores.set(doc, (scores.get(doc) ?? 0) + (idf * tf) / (tf + 1.2));
}
// numeric comparator is mandatory: bare sort() compares stringified values
return [...scores].sort((a, b) => b[1] - a[1]).slice(0, k);
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Search Engine?
Map<string, Map<number, number>> is the right container -- a plain object coerces every key to a string and reorders integer-like ones. Intl.Segmenter with {granularity: 'word'} does real word segmentation including CJK, and every segment carries an isWordLike flag that a /\w+/ regex cannot give you. String.prototype.normalize('NFKC') folds full-width and compatibility forms before you lowercase. The platform ships no stemmer and no BM25: lunr, minisearch and flexsearch are the ecosystem answers, and SQLite FTS5 through better-sqlite3 once the index leaves memory.
What is the most common JavaScript mistake when implementing Search Engine?
Array.prototype.sort with no comparator converts every element to a string and compares UTF-16 code units. A postings list sorted as [2, 10, 9] comes back [10, 2, 9], and a galloping intersection that assumes ascending numeric doc ids then returns the wrong document set -- no exception, just plausible-looking wrong results that pass on a ten-document fixture. Always pass (a, b) => a - b. The sibling trap: a plain object used as postings reorders integer-like keys into ascending numeric order regardless of insertion order, so Object.keys() is not your term order and never was.
How does Search Engine actually perform in JavaScript?
V8 caches a string's hash on the string object, so repeated Map lookups of the same token do not rehash -- token reuse is nearly free, novel tokens are not. Strings are UTF-16, so .length counts code units and an emoji costs 2; budget index memory on code units, not characters. Postings held in an Int32Array instead of Array<number> drop from an 8-byte tagged slot per element to 4 bytes and lose the elements-kind transition risk entirely, roughly halving resident size. Sorting pays one JS call per comparison, and the gap is not just a constant factor: a full sort is O(n log n) while a bounded k-sized heap is O(n log k) -- at a million candidates and k = 10 that is roughly 20 comparisons per candidate against 3. Time complexity is O(n log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.