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

Method slice

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

1010 * Throws error if the indices are for characters that were already removed.
1011 */
1012 slice(start: number = 0, end: number = this.original.length - this.offset): string {
1013 start = start + this.offset
1014 end = end + this.offset
1015
1016 if (this.original.length !== 0) {
1017 if (start < 0)
1018 start = Math.max(0, start + this.original.length)
1019 if (end < 0)
1020 end = Math.max(0, end + this.original.length)
1021 }
1022
1023 let result = ''
1024
1025 // find start chunk
1026 let chunk = this.firstChunk
1027 while (chunk && (chunk.start > start || chunk.end <= start)) {
1028 // found end chunk before start
1029 if (chunk.start < end && chunk.end >= end) {
1030 return result
1031 }
1032
1033 chunk = chunk.next
1034 }
1035
1036 if (chunk && chunk.edited && chunk.start !== start) {
1037 throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`)
1038 }
1039
1040 const startChunk = chunk
1041 while (chunk) {
1042 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1043 result += chunk.intro
1044 }
1045
1046 const containsEnd = chunk.start < end && chunk.end >= end
1047 if (containsEnd && chunk.edited && chunk.end !== end) {
1048 throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`)
1049 }
1050
1051 const sliceStart = startChunk === chunk ? start - chunk.start : 0
1052 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length
1053
1054 result += chunk.content.slice(sliceStart, sliceEnd)
1055
1056 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1057 result += chunk.outro
1058 }
1059
1060 if (containsEnd) {
1061 break
1062 }
1063
1064 chunk = chunk.next
1065 }
1066
1067 return result
1068 }
1069

Callers 9

indentMethod · 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