Overview
TheoptimizeRules function analyzes an array of rules and automatically consolidates redundant patterns, returning an optimized rule set along with statistics and warnings. This reduces the size of your rule set and improves trie build performance.
Function signature
Parameters
Array of rules to optimize. Each rule should follow the same structure used in buildTrie.
Optional build configuration affecting optimization:
Returns
The optimization result including optimized rules, savings statistics, and warnings:
Optimizations performed
1. Case sensitivity consolidation
Detects sources that differ only in case and consolidates them into a single source withcasing: CaseSensitivity.Insensitive.
2. Apostrophe normalization
WhennormalizeApostrophes: true is set, consolidates sources that differ only in apostrophe-like characters.
3. Prefix optimization
Detects redundant prefix variations and adds aprefix option instead.
4. Clip pattern optimization
Detects leading/trailing apostrophe-like characters and addsclipStartPattern / clipEndPattern options.
5. Subset elimination
Removes rules whose sources are a subset of another rule with the same target.6. Conflict detection
Warns when the same source maps to different targets.7. Match type consolidation
Merges rules with differentMatchType values for the same source/target, keeping the most permissive.
Example usage
Basic usage
With apostrophe normalization
Handling conflicts
Using optimized rules with buildTrie
Implementation details
The optimization process follows these steps:- Match type conflict handling - Consolidates rules with different match types for the same source/target
- Target grouping - Groups rules by target value and options for analysis
- Group optimization - For each group:
- Deduplicates exact matches
- Consolidates apostrophe variants
- Detects case consolidation opportunities
- Optimizes prefix usage
- Optimizes clip patterns
- Subset removal - Eliminates redundant subset rules
- Conflict detection - Identifies sources mapping to different targets
Runtime complexity
The complexity depends on the optimization steps:- Grouping: O(n · m) where n = number of rules, m = average sources per rule
- Per-group optimization: O(m²) for comparison operations
- Subset removal: O(n²) for pairwise rule comparison
Best practices
- Always run optimization before building the trie - This reduces build time and memory usage
- Review warnings - Check conflicts and overwritten rules to ensure your rule set behaves as expected
- Use apostrophe normalization - If your rules contain apostrophe variations, enable this option
- Monitor savings - Track the number of sources/rules removed to measure optimization impact
Related functions
- buildTrie - Uses the optimized rules to build a trie
- containsTarget - Can verify targets after optimization
- searchAndReplace - Uses the trie built from optimized rules