设计一个带光标的文本编辑器,它可以实现以下功能:
添加:在光标所在处添加文本。
删除:在光标所在处删除文本(模拟键盘的删除键)。
移动:将光标往左或者往右移动。 当删除文本时,只有光标左边的字符会被删除。光标会留在文本内,也就是说任意时候 0 <= cursor.position <= currentText.length 都成立。
请你实现 TextEditor 类。
class TextEditor {
constructor() {
this.currentText = ''; // 当前文本
this.cursorPosition = 0; // 光标位置
}
// text 添加到光标所在位置, 添加完后光标在 text 的右边
addText(text) {}
// 删除光标左边 k 个字符,返回实际删除的字符数目
deleteText(k) {}
// 将光标向左移动 k 次。返回移动后光标左边 min(10, len) 个字符,其中 len 是光标左边的字符数目
cursorLeft(k) {}
// 将光标向右移动 k 次。返回移动后光标左边 min(10, len) 个字符,其中 len 是光标左边的字符数目。
cursorRight(k) {}
}
class TextEditor {
constructor() {
this.currentText = ''; // 当前文本
this.cursorPosition = 0; // 光标位置
}
// text 添加到光标所在位置, 添加完后光标在 text 的右边
addText(text) {
const leftText = this.currentText.slice(0, this.cursorPosition);
const rightText = this.currentText.slice(this.cursorPosition);
this.currentText = leftText + text + rightText;
this.cursorPosition += text.length;
}
// 删除光标左边 k 个字符,返回实际删除的字符数目
deleteText(k) {
const leftText = this.currentText.slice(0, this.cursorPosition);
const deletedText = leftText.slice(-k);
this.currentText = leftText.slice(0, -k) + this.currentText.slice(this.cursorPosition);
this.cursorPosition -= deletedText.length;
return deletedText.length;
}
// 将光标向左移动 k 次。返回移动后光标左边 min(10, len) 个字符,其中 len 是光标左边的字符数目
cursorLeft(k) {
this.cursorPosition = Math.max(0, this.cursorPosition - k);
return this.currentText.slice(Math.max(0, this.cursorPosition - 10), this.cursorPosition);
}
// 将光标向右移动 k 次。返回移动后光标左边 min(10, len) 个字符,其中 len 是光标左边的字符数目。
cursorRight(k) {
this.cursorPosition = Math.min(this.currentText.length, this.cursorPosition + k);
return this.currentText.slice(Math.max(0, this.cursorPosition - 10), this.cursorPosition);
}
}