MCPcopy Create free account
hub / github.com/Rich-Harris/magic-string / slice

Method slice

src/MagicString.ts:1101–1163  ·  view source on GitHub ↗

* Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. * Throws error if the indices are for characters that were already removed.

(start: number = 0, end: number = this.original.length - this.offset)

Source from the content-addressed store, hash-verified

1099 * Throws error if the indices are for characters that were already removed.
1100 */
1101 slice(start: number = 0, end: number = this.original.length - this.offset): string {
1102 start = start + this.offset
1103 end = end + this.offset
1104
1105 if (this.original.length !== 0) {
1106 if (start < 0)
1107 start = Math.max(0, start + this.original.length)
1108 if (end < 0)
1109 end = Math.max(0, end + this.original.length)
1110 }
1111
1112 let result = ''
1113
1114 // find start chunk
1115 let chunk = this.firstChunk
1116 while (chunk && (chunk.start > start || chunk.end <= start)) {
1117 // found end chunk before start
1118 if ((chunk.start < end && chunk.end >= end) || (end === 0 && chunk.start === 0)) {
1119 return result
1120 }
1121
1122 chunk = chunk.next
1123 }
1124
1125 if (chunk && chunk.edited && chunk.start !== start) {
1126 throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`)
1127 }
1128
1129 const startChunk = chunk
1130 while (chunk) {
1131 // for end === 0 the slice ends at the very start of the original, so stop
1132 // once the walk reaches the chunk holding that position, taking nothing from it
1133 if (end === 0 && chunk.start === 0) {
1134 break
1135 }
1136
1137 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1138 result += chunk.intro
1139 }
1140
1141 const containsEnd = chunk.start < end && chunk.end >= end
1142 if (containsEnd && chunk.edited && chunk.end !== end) {
1143 throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`)
1144 }
1145
1146 const sliceStart = startChunk === chunk ? start - chunk.start : 0
1147 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length
1148
1149 result += chunk.content.slice(sliceStart, sliceEnd)
1150
1151 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1152 result += chunk.outro
1153 }
1154
1155 if (containsEnd) {
1156 break
1157 }
1158

Callers 10

indentMethod · 0.45
SourceMap.test.tsFile · 0.45
expandReplacementFunction · 0.45
cloneMethod · 0.45
updateMethod · 0.45
getReplacementMethod · 0.45
_replaceAllStringMethod · 0.45
constructorMethod · 0.45
splitMethod · 0.45
addEditMethod · 0.45

Calls

no outgoing calls

Tested by

no test coverage detected