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