Javascript 用方法编写一个类

Javascript 用方法编写一个类,javascript,class,methods,Javascript,Class,Methods,我正在努力编写一个包含一些方法的类。我不确定我做错了什么 为了创建此类,我需要查看以下测试: "严格使用",; 常量编辑器=需要“../Editor”; const{expect}=require'chai'; 描述“编辑”,=>{ 它“允许用户编写文本”,=>{ 常量编辑器=新编辑器; 编辑:写“你好,codez”; expecteditor.toString.to.equal'Hello-codez'; 编辑:写“摩尔”; expecteditor.toString.to.equal'He

我正在努力编写一个包含一些方法的类。我不确定我做错了什么

为了创建此类,我需要查看以下测试:

"严格使用",; 常量编辑器=需要“../Editor”; const{expect}=require'chai'; 描述“编辑”,=>{ 它“允许用户编写文本”,=>{ 常量编辑器=新编辑器; 编辑:写“你好,codez”; expecteditor.toString.to.equal'Hello-codez'; 编辑:写“摩尔”; expecteditor.toString.to.equal'Hello-codezmoar'; }; xit'允许用户撤消写入',=>{ 常量编辑器=新编辑器; 编辑:写“你好,codez”; expecteditor.toString.to.equal'Hello-codez'; 编辑:写“摩尔的东西”; expecteditor.toString.to.equal'Hello-codezMoar stuff'; 编辑:写“更多”; expecteditor.toString.to.equal'Hello-codezMoar stuff甚至更多'; editor.undo; expecteditor.toString.to.equal'Hello-codezMoar stuff'; editor.undo; expecteditor.toString.to.equal'Hello-codez'; editor.undo; expecteditor.toString.to.equal; }; xit'允许用户查找和替换',=>{ 常量编辑器=新编辑器; 编辑,写“富的东西”; 编者:写“其他富”; 编辑器。替换“foo”、“bar”; expecteditor.toString.to.equal'bar stuff other bar'; }; xit‘允许撤消替换’,=>{ 常量编辑器=新编辑器; 编辑,写“富的东西”; 编者:写“其他富”; 编辑器。替换“foo”、“bar”; expecteditor.toString.to.equal'bar stuff other bar'; editor.undo; expecteditor.toString.to.equal'foo-stuff-other-foo'; editor.undo; expecteditor.toString.to.equal'foo-stuff'; }; xit'允许用户重做',=>{ 常量编辑器=新编辑器; 编辑,写“富的东西”; 编者:写“其他富”; 编辑器。替换“foo”、“bar”; expecteditor.toString.to.equal'bar stuff other bar'; editor.undo; expecteditor.toString.to.equal'foo-stuff-other-foo'; editor.undo; expecteditor.toString.to.equal'foo-stuff'; editor.redo; expecteditor.toString.to.equal'foo-stuff-other-foo'; editor.redo; expecteditor.toString.to.equal'bar stuff other bar'; }; };
您需要保留编辑器字符串的历史记录…

this.str+=text。。。toString{returnthis.str;}谢谢你写了Jonas。你能再解释一下你是如何创建状态和撤销数组的吗?你的解决方案很好。我想确保我了解它在做什么。@ivonne terrero若要撤消更改,您可以非常复杂地跟踪更改,或者只存储所有状态。我们存储的最后一个状态将在撤消时恢复,因此它的First-in-last-out=>我们需要一个堆栈push/pop。同样的原则也适用于重做。
class Editor {
  constructor (str) {
    this.str = str;
    this.states = [""]; //for undo
    this.undos = [];
  }
  write(text) {
    this.undos = [];
    this.states.push(this.str);
    this.str += text;
  }
  undo(){
    this.undos.push(this.str);
    this.str = this.states.pop() || "";
  }
  redo(){
    if(this.undos.length){
      this.states.push(this.str);
      this.str = this.undos.pop();
    }
  }
  replace(a,b){
    this.states.push(this.str);
    this.str = this.str.split(a).join(b);
  }
  toString(){
    return this.str;
  }
}