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

Method slice

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

867 * Throws error if the indices are for characters that were already removed.
868 */
869 slice(start: number = 0, end: number = this.original.length - this.offset): string {
870 start = start + this.offset
871 end = end + this.offset
872
873 if (this.original.length !== 0) {
874 while (start < 0) start += this.original.length
875 while (end < 0) end += this.original.length
876 }
877
878 let result = ''
879
880 // find start chunk
881 let chunk = this.firstChunk
882 while (chunk && (chunk.start > start || chunk.end <= start)) {
883 // found end chunk before start
884 if (chunk.start < end && chunk.end >= end) {
885 return result
886 }
887
888 chunk = chunk.next
889 }
890
891 if (chunk && chunk.edited && chunk.start !== start) {
892 throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`)
893 }
894
895 const startChunk = chunk
896 while (chunk) {
897 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
898 result += chunk.intro
899 }
900
901 const containsEnd = chunk.start < end && chunk.end >= end
902 if (containsEnd && chunk.edited && chunk.end !== end) {
903 throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`)
904 }
905
906 const sliceStart = startChunk === chunk ? start - chunk.start : 0
907 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length
908
909 result += chunk.content.slice(sliceStart, sliceEnd)
910
911 if (chunk.outro && (!containsEnd || chunk.end === end)) {
912 result += chunk.outro
913 }
914
915 if (containsEnd) {
916 break
917 }
918
919 chunk = chunk.next
920 }
921
922 return result
923 }
924
925 // TODO deprecate this? not really very useful
926 /**

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