0

Why the clear function doesn't work. I am not sure what I am doing wrong? Any help is appreciated. Regards Yusuf

    function StringBuilder(initials) {
      var list = [];
      if (initials) {
        list.push(initials);
      }
      return {
        append: function (str) {
          if (!str) {
            str = "";
          }
          list.push(str);
          return this;
        },
        appendLine: function (str) {
          if (!str) {
            str = "";
          }
          list.push(str + "\n");
          return this;
        },
        clear: function () {
          this.list = [];
          return this;
        },
        toString: function () {
          return list.toString().replace(/,/g, " ");
        }
      };
    }

5
  • "doesn't work" is vague. Can you describe specifically what's happening? Commented Apr 7, 2018 at 15:00
  • It doesn't clear the list Commented Apr 7, 2018 at 15:01
  • Why are you returning this? also please show how you are calling your code. Commented Apr 7, 2018 at 15:03
  • @ngeksyo probably so he can write sb.append("hello").append("world") Commented Apr 7, 2018 at 15:04
  • I saw the issue, on the clear function remove this. in the this.list = [] Commented Apr 7, 2018 at 15:06

1 Answer 1

2

Your clear() method resets this.list, but list is not an object property; it's a variable in the closure. The code should be just

    clear: function () {
      list = [];
      return this;
    },
Sign up to request clarification or add additional context in comments.

4 Comments

Also note that list.join("") is a little shorter than calling .toString() and .replace().
Thanks for the hint as well
Also, what is the difference between var sb = new StringBuilder() and var sb = StringBuilder() ?
@YusufCelik there is no difference, because your function always returns a new object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.