Skip to main content

Overview

The buildTrie function constructs a trie data structure from an array of rules. This trie is used to efficiently search through text and replace specified source words with their corresponding target words.

Function signature

buildTrie(rules: Rule[], buildOptions?: BuildTrieOptions): TrieNode

Parameters

rules
Rule[]
required
Array of search and replace rules to build the trie from. Each rule contains:
buildOptions
BuildTrieOptions
Optional build configuration:

Returns

trie
TrieNode
The constructed trie with build options stored for use during search operations. The root node of the trie data structure represents the rules for search and replacement.

Example usage

Basic usage

import { buildTrie } from 'trie-rules';

const rules = [
  {
    from: ['example', 'sample'],
    to: 'demo',
  },
  {
    from: ['specificword'],
    to: 'replacement',
    options: {
      match: MatchType.Whole,
    },
  },
];

const trie = buildTrie(rules);

With apostrophe normalization

import { buildTrie, MatchType } from 'trie-rules';

const rules = [
  {
    from: ["al-Qur'an"],
    to: 'al-Qurʾān',
    options: {
      match: MatchType.Whole,
    },
  },
  {
    from: ["Ka'bah"],
    to: 'Kaʿbah',
  },
];

// Build trie with apostrophe normalization enabled
const trie = buildTrie(rules, { normalizeApostrophes: true });

// The trie can now match "al-Qur'an", "al-Qur`an", etc.

With case-insensitive matching

import { buildTrie, CaseSensitivity } from 'trie-rules';

const rules = [
  {
    from: ['testword'],
    to: 'tested',
    options: {
      casing: CaseSensitivity.Insensitive,
    },
  },
];

const trie = buildTrie(rules);
// Will match 'testword', 'TestWord', 'TESTWORD', etc.

Implementation details

The function processes each rule by:
  1. Applying apostrophe normalization if enabled
  2. Generating case variants for case-insensitive rules
  3. Inserting each source string into the trie structure
  4. Storing build options at the root for use during search operations

Runtime complexity

The complexity is O(n · m · k) where:
  • n = number of rules
  • m = average number of source words per rule
  • k = average length of source words
This represents the total number of characters across all source words in all rules.

Build docs developers (and LLMs) love