Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Text Search Engine Implementation in JavaScript

19 min readadvanced
Website QA and SEO audits

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

An in-memory full-text index that answers "which documents contain this substring" without rescanning the corpus. Concatenate every document into one byte buffer, sort all n suffixes by prefix doubling, and keep two things: the suffix array of offsets and the document-start boundaries. Written the way every snippet here writes it, with a comparison sort inside each of the log n rounds, that build is O(n log^2 n); radix-sorting each round brings it to O(n log n), and SA-IS, which is what Go's index/suffixarray uses, is linear. The index itself is O(n) space. Any pattern of length m is then a contiguous range of the suffix array, found by two binary searches in O(m log n). You reach for this instead of an inverted index when queries are infix, code-like, or in a language you cannot reliably tokenize.

Text Search Engine in JavaScript: what you actually reach for

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.

JavaScript implementation

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. Building the corpus with += in a loop and then indexing it is flagged too: the engine keeps that as a rope until something forces a flatten.
javascript
// 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 Free

The JavaScript-specific 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]. 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.

Performance in JavaScript, beyond the O(n log n)

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. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Text Search Engine between languages.

Real-World Applications

Text Search Engine applies wherever its problem shape appears in your own code. In JavaScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Text Search Engine helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Text Search Engine appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Text Search Engine over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Text Search Engine to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.