* Returns the content of the generated string that corresponds to the slice * between `start` and `end` of the original string, walking the generated * string from the chunk holding `start` to the chunk holding `end`. Throws * if either index falls inside replaced content. After `move()`, a
(start: number = 0, end: number = this.original.length - this.offset)
| 1030 | * whose end now comes before its start in the output yields `''`. |
| 1031 | */ |
| 1032 | slice(start: number = 0, end: number = this.original.length - this.offset): string { |
| 1033 | start = this._resolveIndex(start) |
| 1034 | end = this._resolveIndex(end) |
| 1035 | |
| 1036 | let result = '' |
| 1037 | |
| 1038 | let chunk: Chunk | null | undefined |
| 1039 | if (this.hasMovedChunks) { |
| 1040 | // chunks are no longer in original order, so "the chunk holding `end` |
| 1041 | // comes before the chunk holding `start`" has to be discovered by walking |
| 1042 | // the output: that case yields an empty slice |
| 1043 | chunk = this.firstChunk |
| 1044 | while (chunk && (chunk.start > start || chunk.end <= start)) { |
| 1045 | if ((chunk.start < end && chunk.end >= end) || (end === 0 && chunk.start === 0)) { |
| 1046 | return result |
| 1047 | } |
| 1048 | chunk = chunk.next |
| 1049 | } |
| 1050 | } |
| 1051 | else { |
| 1052 | // in original order the end chunk precedes the start chunk exactly when |
| 1053 | // start >= end, which is the empty slice |
| 1054 | if (start >= end) |
| 1055 | return result |
| 1056 | chunk = this._chunkAt(start) |
| 1057 | } |
| 1058 | |
| 1059 | if (chunk && chunk.edited && chunk.start !== start) { |
| 1060 | throw new MagicStringError(`cannot use edited character ${start} as slice start anchor`) |
| 1061 | } |
| 1062 | |
| 1063 | const startChunk = chunk |
| 1064 | while (chunk) { |
| 1065 | // for end === 0 the slice ends at the very start of the original, so stop |
| 1066 | // once the walk reaches the chunk holding that position, taking nothing from it |
| 1067 | if (end === 0 && chunk.start === 0) { |
| 1068 | break |
| 1069 | } |
| 1070 | |
| 1071 | if (chunk.intro && (startChunk !== chunk || chunk.start === start)) { |
| 1072 | result += chunk.intro |
| 1073 | } |
| 1074 | |
| 1075 | const containsEnd = chunk.start < end && chunk.end >= end |
| 1076 | if (containsEnd && chunk.edited && chunk.end !== end) { |
| 1077 | throw new MagicStringError(`cannot use edited character ${end} as slice end anchor`) |
| 1078 | } |
| 1079 | |
| 1080 | const sliceStart = startChunk === chunk ? start - chunk.start : 0 |
| 1081 | const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length |
| 1082 | |
| 1083 | result += chunk.content.slice(sliceStart, sliceEnd) |
| 1084 | |
| 1085 | if (chunk.outro && (!containsEnd || chunk.end === end)) { |
| 1086 | result += chunk.outro |
| 1087 | } |
| 1088 | |
| 1089 | if (containsEnd) { |
no test coverage detected