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

Method slice

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

904 * Throws error if the indices are for characters that were already removed.
905 */
906 slice(start: number = 0, end: number = this.original.length - this.offset): string {
907 start = start + this.offset
908 end = end + this.offset
909
910 if (this.original.length !== 0) {
911 if (start < 0)
912 start = Math.max(0, start + this.original.length)
913 if (end < 0)
914 end = Math.max(0, end + this.original.length)
915 }
916
917 let result = ''
918
919 // find start chunk
920 let chunk = this.firstChunk
921 while (chunk && (chunk.start > start || chunk.end <= start)) {
922 // found end chunk before start
923 if (chunk.start < end && chunk.end >= end) {
924 return result
925 }
926
927 chunk = chunk.next
928 }
929
930 if (chunk && chunk.edited && chunk.start !== start) {
931 throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`)
932 }
933
934 const startChunk = chunk
935 while (chunk) {
936 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
937 result += chunk.intro
938 }
939
940 const containsEnd = chunk.start < end && chunk.end >= end
941 if (containsEnd && chunk.edited && chunk.end !== end) {
942 throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`)
943 }
944
945 const sliceStart = startChunk === chunk ? start - chunk.start : 0
946 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length
947
948 result += chunk.content.slice(sliceStart, sliceEnd)
949
950 if (chunk.outro && (!containsEnd || chunk.end === end)) {
951 result += chunk.outro
952 }
953
954 if (containsEnd) {
955 break
956 }
957
958 chunk = chunk.next
959 }
960
961 return result
962 }
963

Callers 8

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