| 7 | * kept per original character instead of per chunk. See README.md for the rules. |
| 8 | */ |
| 9 | export class EditModel { |
| 10 | readonly original: string |
| 11 | /** Output owned by each original char: '' when removed or emptied, the replacement on a holder */ |
| 12 | text: string[] |
| 13 | edited: boolean[] |
| 14 | /** For the holder of a non-empty replacement, the end of its first chunk at edit time; -1 otherwise */ |
| 15 | holderEnd: number[] |
| 16 | /** Inserts left of each boundary; `left[0]` is the string intro */ |
| 17 | left: string[] |
| 18 | /** Inserts right of each boundary; `right[n]` is the string outro */ |
| 19 | right: string[] |
| 20 | /** Every index a split has happened at */ |
| 21 | boundaries: Set<number> |
| 22 | |
| 23 | constructor(original: string) { |
| 24 | const n = original.length |
| 25 | this.original = original |
| 26 | this.text = [...original] |
| 27 | this.edited = Array.from<boolean>({ length: n }).fill(false) |
| 28 | this.holderEnd = Array.from<number>({ length: n }).fill(-1) |
| 29 | this.left = Array.from<string>({ length: n + 1 }).fill('') |
| 30 | this.right = Array.from<string>({ length: n + 1 }).fill('') |
| 31 | this.boundaries = new Set([0, n]) |
| 32 | } |
| 33 | |
| 34 | split(index: number): void { |
| 35 | if (this.boundaries.has(index)) |
| 36 | return |
| 37 | if (this.isInsideHolder(index)) |
| 38 | throw new EditModelError('cannot split a chunk that has already been edited') |
| 39 | this.boundaries.add(index) |
| 40 | } |
| 41 | |
| 42 | append(content: string): void { |
| 43 | this.right[this.original.length] += content |
| 44 | } |
| 45 | |
| 46 | prepend(content: string): void { |
| 47 | this.left[0] = content + this.left[0] |
| 48 | } |
| 49 | |
| 50 | appendLeft(index: number, content: string): void { |
| 51 | this.split(index) |
| 52 | this.left[index] += content |
| 53 | } |
| 54 | |
| 55 | prependLeft(index: number, content: string): void { |
| 56 | this.split(index) |
| 57 | this.left[index] = content + this.left[index] |
| 58 | } |
| 59 | |
| 60 | appendRight(index: number, content: string): void { |
| 61 | this.split(index) |
| 62 | this.right[index] += content |
| 63 | } |
| 64 | |
| 65 | prependRight(index: number, content: string): void { |
| 66 | this.split(index) |
nothing calls this directly
no outgoing calls
no test coverage detected