(
startIndex: number,
endIndex: number = this._string.length
)
| 99 | } |
| 100 | |
| 101 | slice( |
| 102 | startIndex: number, |
| 103 | endIndex: number = this._string.length |
| 104 | ): SpannedString<T> { |
| 105 | if (startIndex < 0 || endIndex < 0) { |
| 106 | throw new Error('Invalid start or end index'); |
| 107 | } |
| 108 | if (startIndex > this._string.length) { |
| 109 | startIndex = this._string.length; |
| 110 | } |
| 111 | if (endIndex > this._string.length) { |
| 112 | endIndex = this._string.length; |
| 113 | } |
| 114 | |
| 115 | let index = 0; |
| 116 | const activeSpansById = new Map<number, Span<T>>(); |
| 117 | const updatedActiveSpans = () => { |
| 118 | for (const span of this._spanMarkers[index] ?? []) { |
| 119 | if (span.isStart) { |
| 120 | activeSpansById.set(span.id, span); |
| 121 | } else { |
| 122 | activeSpansById.delete(span.id); |
| 123 | } |
| 124 | } |
| 125 | }; |
| 126 | const getActiveSpans = () => { |
| 127 | return [...activeSpansById.values()]; |
| 128 | }; |
| 129 | |
| 130 | const newSpanMarkers: (Span<T>[] | undefined)[] = new Array( |
| 131 | endIndex + 1 - startIndex |
| 132 | ); |
| 133 | |
| 134 | // Collect all the active spans before the new string starts |
| 135 | while (index < startIndex) { |
| 136 | updatedActiveSpans(); |
| 137 | index++; |
| 138 | } |
| 139 | newSpanMarkers[0] = getActiveSpans().map((span) => ({ ...span })); |
| 140 | |
| 141 | // Copy over spans active in the new string |
| 142 | while (index < endIndex) { |
| 143 | const spans = this._spanMarkers[index]; |
| 144 | updatedActiveSpans(); |
| 145 | if (spans) { |
| 146 | const newIndex = index - startIndex; |
| 147 | newSpanMarkers[newIndex] = newSpanMarkers[newIndex] ?? []; |
| 148 | newSpanMarkers[newIndex]!.push(...spans); |
| 149 | } |
| 150 | index++; |
| 151 | } |
| 152 | |
| 153 | // Close any spans that are still active at the end of the new string |
| 154 | newSpanMarkers[endIndex - startIndex] = getActiveSpans().map( |
| 155 | (span) => ({ ...span, isStart: false }) |
| 156 | ); |
| 157 | |
| 158 | return new SpannedString<T>( |
no outgoing calls
no test coverage detected