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

Method slice

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

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

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