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

Method slice

src/MagicString.ts:1099–1161  ·  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

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

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