-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
68 lines (62 loc) · 2.16 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
export default class TextEditor {
constructor() {}
#left = "";
#right = "";
#position = 0;
get #length() {
return this.#left.length + this.#right.length;
}
#get(index: number) {
if (index < this.#left.length) {
return this.#left[index];
}
return this.#right[index - this.#left.length];
}
#slice(start = 0, end: number = this.#length): string {
start = Math.max(0, start);
end = Math.min(end, this.#length);
return Array(end - start)
.fill("")
.map((_, i) => this.#get(i + start))
.join("");
}
addText(text: string): void {
if (this.#position === this.#left.length) {
this.#left += text;
this.#position = this.#left.length;
} else {
const all_text = this.#left + this.#right;
this.#right = all_text.slice(this.#position, this.#length);
this.#left = all_text.slice(0, this.#position) + text;
this.#position = this.#left.length;
}
}
deleteText(k: number): number {
if (this.#position === this.#left.length) {
const count = Math.min(k, this.#left.length);
const end = Math.max(0, this.#left.length - k);
this.#left = this.#left.slice(0, end);
this.#position = this.#left.length;
return count;
} else {
const all_text = this.#left + this.#right;
const count = Math.min(k, this.#position);
this.#right = all_text.slice(this.#position, this.#length);
const end = Math.max(0, this.#position - k);
this.#left = all_text.slice(0, end);
this.#position = this.#left.length;
return count;
}
}
cursorLeft(k: number): string {
this.#position = Math.max(0, this.#position - k);
return this.#read_left_ten();
}
#read_left_ten(): string {
return this.#slice(Math.max(0, this.#position - 10), this.#position);
}
cursorRight(k: number): string {
this.#position = Math.min(this.#length, this.#position + k);
return this.#read_left_ten();
}
}