|
| 1 | +# Balanced Pair Search Strategy |
| 2 | + |
| 3 | +A search strategy for matching **balanced delimiter pairs** — including nested occurrences — by layering nesting-level tracking on top of the [`StringAnchorSearchStrategy`](../looped-indexOf-anchored/README.md). |
| 4 | + |
| 5 | +## Algorithm Overview |
| 6 | + |
| 7 | +This strategy finds opening/closing delimiter pairs where nesting is meaningful: the match only completes when every opening delimiter inside it has a corresponding closing delimiter. For example: |
| 8 | + |
| 9 | +- `(`, `)` matches `(content)`, `((a) b)`, `(((deep)))` |
| 10 | +- `{{`, `}}` matches `{{value}}`, `{{{{nested}}}}` |
| 11 | +- `[`, `]` matches `[outer [inner] rest]` |
| 12 | + |
| 13 | +A simple anchor search would match the _first_ closing delimiter after the opening, producing incomplete matches in nested input. `BalancedPairSearchStrategy` extends that underlying search so every inner pair is counted and the match only closes when the depth returns to zero. |
| 14 | + |
| 15 | +### Nesting Detection |
| 16 | + |
| 17 | +``` |
| 18 | +Opening: "(" Closing: ")" |
| 19 | +Input: "((inner) outer)" |
| 20 | +
|
| 21 | + Position: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
| 22 | + Char: ( ( i n n e r ) o u t e r ) |
| 23 | + ↑ ↑ ↑ |
| 24 | + match starts first ) outer ) |
| 25 | + nestingLevel=0 found found |
| 26 | +
|
| 27 | + On first ) at position 7: |
| 28 | + nestingLevel-- → -1 |
| 29 | + Count "(" in "((inner)": two openings → nestingLevel = -1 + 2 = 1 |
| 30 | + Not yet balanced (nestingLevel > 0) — keep looking for more ")" |
| 31 | +
|
| 32 | + On outer ) at position 14: |
| 33 | + nestingLevel-- → 0 |
| 34 | + Count "(" in " outer)": zero openings → nestingLevel = 0 |
| 35 | + Balanced! Yield "((inner) outer)" as a match |
| 36 | +``` |
| 37 | + |
| 38 | +**Without nesting awareness:** |
| 39 | + |
| 40 | +``` |
| 41 | +Anchor strategy alone: |
| 42 | + Input: "((inner) outer)" |
| 43 | + Match: "((inner)" ← stops at first ), incomplete! |
| 44 | +``` |
| 45 | + |
| 46 | +## Implementation Details |
| 47 | + |
| 48 | +`BalancedPairSearchStrategy` wraps `LoopedIndexOfAnchoredSearchStrategy` and post-processes each match it yields: |
| 49 | + |
| 50 | +```typescript |
| 51 | +class BalancedPairSearchStrategy implements SearchStrategy< |
| 52 | + BalancedPairSearchState, |
| 53 | + string |
| 54 | +> { |
| 55 | + private anchorStringSearchStrategy: LoopedIndexOfAnchoredSearchStrategy; |
| 56 | + |
| 57 | + constructor(opening: string, closing: string) { |
| 58 | + this.anchorStringSearchStrategy = new LoopedIndexOfAnchoredSearchStrategy([ |
| 59 | + opening, |
| 60 | + closing |
| 61 | + ]); |
| 62 | + } |
| 63 | +} |
| 64 | +``` |
| 65 | + |
| 66 | +When the underlying anchor strategy yields a match (opening–closing pair found), the balanced pair strategy: |
| 67 | + |
| 68 | +1. Counts any additional opening delimiters within the new match content |
| 69 | +2. Adjusts `nestingLevel` accordingly |
| 70 | +3. If `nestingLevel > 0`, resets `currentNeedleIndex = 1` on the shared state so the anchor strategy resumes scanning for the next closing delimiter — without discarding already-accumulated match content |
| 71 | +4. Accumulates content in `balancedBuffer` until `nestingLevel` returns to zero, then yields the whole span as a single match |
| 72 | + |
| 73 | +### Incremental Content Tracking |
| 74 | + |
| 75 | +The underlying anchor strategy's match content grows cumulatively (from the first opening needle to each subsequent closing needle). The balanced pair strategy slices only the _new_ portion of each yielded match to count openings in it: |
| 76 | + |
| 77 | +```typescript |
| 78 | +const newContent = matchResult.content.slice(prevMatchLength); |
| 79 | +prevMatchLength = matchResult.content.length; |
| 80 | +// ... |
| 81 | +state.nestingLevel--; |
| 82 | +let cursor = 0; |
| 83 | +while ((cursor = newContent.indexOf(this.opening, cursor)) !== -1) { |
| 84 | + state.nestingLevel++; |
| 85 | + cursor += this.opening.length; |
| 86 | +} |
| 87 | +``` |
| 88 | + |
| 89 | +This ensures each opening is counted exactly once, regardless of how many intermediate closing delimiters were found. |
| 90 | + |
| 91 | +### Inner Buffer Adjustment |
| 92 | + |
| 93 | +When `nestingLevel > 0` and the underlying strategy's buffer still holds in-flight content, the balanced pair strategy trims the anchor strategy's buffer to exclude content already accounted for in `balancedBuffer`: |
| 94 | + |
| 95 | +```typescript |
| 96 | +if (state.nestingLevel > 0) { |
| 97 | + state.buffer = state.buffer.slice(state.balancedBuffer.length); |
| 98 | +} |
| 99 | +``` |
| 100 | + |
| 101 | +This prevents double-counting when the anchor strategy's cross-chunk buffer is combined with the next chunk. |
| 102 | + |
| 103 | +## State Management |
| 104 | + |
| 105 | +`BalancedPairSearchState` extends `LoopedIndexOfAnchoredSearchState`: |
| 106 | + |
| 107 | +```typescript |
| 108 | +interface BalancedPairSearchState extends LoopedIndexOfAnchoredSearchState { |
| 109 | + /** How many unmatched opening delimiters have been seen inside the current match */ |
| 110 | + nestingLevel: number; |
| 111 | + /** Accumulated content of the outermost balanced match in progress */ |
| 112 | + balancedBuffer: string; |
| 113 | + /** Absolute stream offset at which the outermost opening delimiter was found */ |
| 114 | + balancedBufferStart: number; |
| 115 | +} |
| 116 | +``` |
| 117 | + |
| 118 | +**State transitions:** |
| 119 | + |
| 120 | +| Condition | `nestingLevel` | `balancedBuffer` | Action | |
| 121 | +| --------------------------------- | --------------------- | -------------------------- | ----------------------------------- | |
| 122 | +| No match found | unchanged (0) | `""` | Pass through as non-match | |
| 123 | +| Opening found, no inner opens | `0` (after `--` + 0) | accumulated → cleared | Yield as complete match | |
| 124 | +| Opening found, inner opens exist | `> 0` | accumulating | Set `currentNeedleIndex = 1`, continue | |
| 125 | +| Subsequent close balances depth | decrements toward `0` | accumulating | Continue or yield when reaching `0` | |
| 126 | +| Flush mid-match | reset to `0` | cleared (returned as-is) | Return buffered content unflushed | |
| 127 | + |
| 128 | +**Flush behaviour:** |
| 129 | + |
| 130 | +If a stream ends while a balanced match is in progress (e.g. `((inner)` with no outer `)`), `flush` returns all accumulated content in `balancedBuffer` plus any remaining content in the anchor strategy's buffer: |
| 131 | + |
| 132 | +```typescript |
| 133 | +flush(state: BalancedPairSearchState): string { |
| 134 | + const flushed = state.balancedBuffer; |
| 135 | + state.balancedBuffer = ""; |
| 136 | + state.balancedBufferStart = 0; |
| 137 | + state.nestingLevel = 0; |
| 138 | + return flushed + this.anchorStringSearchStrategy.flush(state); |
| 139 | +} |
| 140 | +``` |
| 141 | + |
| 142 | +## Cross-Chunk Matching |
| 143 | + |
| 144 | +The strategy correctly handles matches that span chunk boundaries at every level: |
| 145 | + |
| 146 | +``` |
| 147 | +Opening: "(" Closing: ")" |
| 148 | +Chunk 1: "((inner)" |
| 149 | +Chunk 2: " outer)" |
| 150 | +
|
| 151 | +Process Chunk 1: |
| 152 | + - Anchor strategy finds "((inner)" as match |
| 153 | + - nestingLevel: 0 − 1 + 2 = 1 (two "(" inside, one ")" closes) |
| 154 | + - currentNeedleIndex reset to 1 — continue scanning for ")" |
| 155 | + - balancedBuffer: "((inner)" |
| 156 | +
|
| 157 | +Process Chunk 2: |
| 158 | + - Anchor strategy finds " outer)" as the continuation |
| 159 | + - nestingLevel: 1 − 1 = 0 (no new "(" in " outer)") |
| 160 | + - Balanced! Yield "((inner) outer)", streamIndices: [0, 15] |
| 161 | +``` |
| 162 | + |
| 163 | +## Stream Indices |
| 164 | + |
| 165 | +Matches report `streamIndices` as absolute offsets into the full stream, not relative to the current chunk: |
| 166 | + |
| 167 | +``` |
| 168 | +Stream: "prefix ((inner) outer) suffix" |
| 169 | + 0 7 15 22 |
| 170 | +
|
| 171 | +Match yields: { isMatch: true, content: "((inner) outer)", streamIndices: [7, 22] } |
| 172 | +``` |
| 173 | + |
| 174 | +`streamIndices[0]` is the start of the outermost opening delimiter; `streamIndices[1]` is the end of the outermost closing delimiter (exclusive, following the same convention as [`String.prototype.slice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice)). |
| 175 | + |
| 176 | +## Performance Characteristics |
| 177 | + |
| 178 | +`BalancedPairSearchStrategy` inherits the smart partial-match buffering of `LoopedIndexOfAnchoredSearchStrategy`. The nesting layer adds a linear scan of each new match increment to count opening delimiters, which is proportional to match content size rather than stream size. |
| 179 | + |
| 180 | +| Scenario | Characteristic | |
| 181 | +| -------------------------------- | ------------------------------------------------------------------- | |
| 182 | +| No matches in stream | Same cost as anchor strategy — near-zero buffering overhead | |
| 183 | +| Flat (non-nested) matches | Minimal overhead over anchor strategy — one scan per match | |
| 184 | +| Deeply nested matches | Proportional to depth × average inner-match size | |
| 185 | +| Partial matches at boundaries | Inherits smart buffering — only buffers on genuine partial matches | |
| 186 | + |
| 187 | +## Usage Examples |
| 188 | + |
| 189 | +### Single-Character Delimiters |
| 190 | + |
| 191 | +```typescript |
| 192 | +import { BalancedPairSearchStrategy } from "replace-content-transformer"; |
| 193 | + |
| 194 | +const strategy = new BalancedPairSearchStrategy("(", ")"); |
| 195 | +``` |
| 196 | + |
| 197 | +### Multi-Character Delimiters |
| 198 | + |
| 199 | +```typescript |
| 200 | +// Matches {{value}}, {{{{doubly nested}}}}, etc. |
| 201 | +const strategy = new BalancedPairSearchStrategy("{{", "}}"); |
| 202 | +``` |
| 203 | + |
| 204 | +### With an Engine |
| 205 | + |
| 206 | +```typescript |
| 207 | +import { |
| 208 | + BalancedPairSearchStrategy, |
| 209 | + SyncReplacementTransformEngine |
| 210 | +} from "replace-content-transformer"; |
| 211 | +import { ReplaceContentTransformer } from "replace-content-transformer/web"; |
| 212 | + |
| 213 | +// Replace every top-level balanced `(...)` expression, including nested ones |
| 214 | +const transformer = new ReplaceContentTransformer( |
| 215 | + new SyncReplacementTransformEngine({ |
| 216 | + searchStrategy: new BalancedPairSearchStrategy("(", ")"), |
| 217 | + replacement: (match: string) => `[${match.slice(1, -1)}]` |
| 218 | + }) |
| 219 | +); |
| 220 | +``` |
| 221 | + |
| 222 | +### Detecting Nesting Depth |
| 223 | + |
| 224 | +Since the full matched content is available in the replacement function, nesting depth can be calculated from the match itself: |
| 225 | + |
| 226 | +```typescript |
| 227 | +const strategy = new BalancedPairSearchStrategy("(", ")"); |
| 228 | + |
| 229 | +const transformer = new ReplaceContentTransformer( |
| 230 | + new SyncReplacementTransformEngine({ |
| 231 | + searchStrategy: strategy, |
| 232 | + replacement: (match: string) => { |
| 233 | + const depth = (match.match(/\(/g) ?? []).length; |
| 234 | + return `/* depth ${depth} */${match}`; |
| 235 | + } |
| 236 | + }) |
| 237 | +); |
| 238 | +``` |
0 commit comments