3月美团笔试应用题

本文介绍了如何设计一个TextEditor类,它支持在指定位置添加文本、删除字符、以及左右移动光标,保证光标始终在文本范围内。
摘要由CSDN通过智能技术生成

设计一个带光标的文本编辑器,它可以实现以下功能: 
添加:在光标所在处添加文本。 
删除:在光标所在处删除文本(模拟键盘的删除键)。
移动:将光标往左或者往右移动。 当删除文本时,只有光标左边的字符会被删除。光标会留在文本内,也就是说任意时候 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);
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值