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

Method slice

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

853 * Throws error if the indices are for characters that were already removed.
854 */
855 slice(start: number = 0, end: number = this.original.length - this.offset): string {
856 start = start + this.offset
857 end = end + this.offset
858
859 if (this.original.length !== 0) {
860 while (start < 0) start += this.original.length
861 while (end < 0) end += this.original.length
862 }
863
864 let result = ''
865
866 // find start chunk
867 let chunk = this.firstChunk
868 while (chunk && (chunk.start > start || chunk.end <= start)) {
869 // found end chunk before start
870 if (chunk.start < end && chunk.end >= end) {
871 return result
872 }
873
874 chunk = chunk.next
875 }
876
877 if (chunk && chunk.edited && chunk.start !== start)
878 throw new Error(`Cannot use replaced character ${start} as slice start anchor.`)
879
880 const startChunk = chunk
881 while (chunk) {
882 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
883 result += chunk.intro
884 }
885
886 const containsEnd = chunk.start < end && chunk.end >= end
887 if (containsEnd && chunk.edited && chunk.end !== end)
888 throw new Error(`Cannot use replaced character ${end} as slice end anchor.`)
889
890 const sliceStart = startChunk === chunk ? start - chunk.start : 0
891 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length
892
893 result += chunk.content.slice(sliceStart, sliceEnd)
894
895 if (chunk.outro && (!containsEnd || chunk.end === end)) {
896 result += chunk.outro
897 }
898
899 if (containsEnd) {
900 break
901 }
902
903 chunk = chunk.next
904 }
905
906 return result
907 }
908
909 // TODO deprecate this? not really very useful
910 /**

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