Text 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
- ✓Text Search Engine runs in O(n log n) time and O(n) space, in JavaScript as in every other language.
- ✓Nothing indexed ships with the language. You build on Int32Array for the suffix array (unboxed, contiguous, and its sort has a numeric default), TextEncoder from the global scope to get UTF-8 bytes out of a UTF-16 string, String.prototype.normalize for form folding at ingest, and Intl.Segmenter with granularity 'word' when you need real tokenization instead of a /\w+/ that mangles Thai, Japanese and Khmer.
- ✓A comparator is never optional in review, even when the values are obviously numbers. Reviewers also want typed arrays across the whole index (a plain Array of n offsets stays PACKED_SMI_ELEMENTS and is unboxed, but one write of a non-Smi or one hole transitions the whole array to HOLEY_ELEMENTS and every later read takes the slow path, and you never get the fixed-width buffer you can mmap, transfer to a worker or hand to WASM), no substring or slice inside the doubling loop, offsets returned rather than strings, and Intl.Segmenter rather than a regex once the corpus stops being English.
- ✓The JavaScript trap: Array.prototype.sort with no comparator coerces every element to a string and sorts lexicographically, so [10, 9, 100].sort() gives [10, 100, 9].
- ✓V8 represents str.slice(i) on a long string as a SlicedString: O(1) to make, but it retains the entire parent, so a search result set of 200 snippets can pin a 50 MB document forever.
What Text Search Engine actually is
Text Search Engine in JavaScript: what you actually reach for
JavaScript implementation
// suffix array over UTF-8 bytes; Int32Array keeps offsets unboxed
export function build(bytes) {
const n = bytes.length;
const sa = new Int32Array(n).map((_, i) => i);
let rank = Int32Array.from(bytes);
const nxt = new Int32Array(n);
for (let k = 1; k < n; k <<= 1) {
const at = (i) => (i + k < n ? rank[i + k] : -1);
sa.sort((a, b) => rank[a] - rank[b] || at(a) - at(b)); // comparator is NOT optional
nxt[sa[0]] = 0;
for (let i = 1; i < n; i++) {
const p = sa[i - 1], c = sa[i];
nxt[c] = nxt[p] + (rank[p] !== rank[c] || at(p) !== at(c) ? 1 : 0);
}
rank.set(nxt);
if (rank[sa[n - 1]] === n - 1) break;
}
return sa;
}
export function lowerBound(bytes, sa, pat) {
let lo = 0, hi = sa.length;
while (lo < hi) {
const mid = (lo + hi) >> 1, i = sa[mid];
let d = 0;
for (let j = 0; j < pat.length && d === 0; j++)
d = (i + j < bytes.length ? bytes[i + j] : -1) - pat[j];
if (d < 0) lo = mid + 1; else hi = mid;
}
return lo;
}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 Text Search Engine?
Nothing indexed ships with the language. You build on Int32Array for the suffix array (unboxed, contiguous, and its sort has a numeric default), TextEncoder from the global scope to get UTF-8 bytes out of a UTF-16 string, String.prototype.normalize for form folding at ingest, and Intl.Segmenter with granularity 'word' when you need real tokenization instead of a /\w+/ that mangles Thai, Japanese and Khmer. Intl.Collator gives locale ordering for a term dictionary. For a ready-made inverted index the ecosystem answers are MiniSearch, FlexSearch and Lunr: Lunr is whole-token only and MiniSearch matches prefixes, while FlexSearch does infix with tokenize: 'full' by indexing every substring of every term, so its index blows up superlinearly in term length, which is why a suffix array over the raw bytes stays hand-rolled for code-like corpora.
What is the most common JavaScript mistake when implementing Text Search Engine?
Array.prototype.sort with no comparator coerces every element to a string and sorts lexicographically, so [10, 9, 100].sort() gives [10, 100, 9]. A suffix array is precisely an array of integers, so sa.sort() produces a permutation that still looks plausible, still has the right length, and is silently wrong: your binary search then converges on nothing. The asymmetry is what makes it lethal here, because TypedArray.prototype.sort defaults to numeric ascending. The identical expression is correct on Int32Array and broken on Array, and switching representations mid-refactor flips it without a single error.
How does Text Search Engine actually perform in JavaScript?
V8 represents str.slice(i) on a long string as a SlicedString: O(1) to make, but it retains the entire parent, so a search result set of 200 snippets can pin a 50 MB document forever. Strings built by repeated concatenation are cons-strings and pay a one-time flatten on first character access, usually inside your hottest loop. Comparator callbacks go megamorphic if the same sort is reached with different shapes, which kills inlining. Int32Array#sort with no comparator is an in-place numeric sort with no temporary; the moment you pass a comparator, as the doubling loop must, V8 copies the elements into a temporary work array and runs the same TimSort as Array#sort, so the saving left is the unboxed SMI element reads, not the allocation. 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 trialStudying for this? Replit free tiers and academic plans are laid out 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.