Search code examples
javascriptclassecmascript-6constructor

I need a make text encoder but i have a problem


It should take multiple words and output a combined version, where each word is separated by a dollar sign $.

For example, for the words "hello", "how", "are", "you", the output should be "$hello$how$are$you$".

class Add {
  constructor(...words) {
      this.words = words;
  }
    all(){console.log('$'+ this.words)};
}

var x = new Add("hehe", "hoho", "haha", "hihi", "huhu");
var y = new Add("this", "is", "awesome");
var z = new Add("lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit");

x.all();

output $hehe,hoho,haha,hihi,huhu

expected output

$hehe$hoho$haha$hihi$huhu$
$this$is$awesome$
$lorem$ipsum$dolor$sit$amet$consectetur$adipiscing$elit$

Solution

  • Right now you are concatenating the toString of the array to the dollar sign. That will add a comma-delimited string to it.

    Instead you could use Array.join

    class Add {
      constructor(...words) {
        this.words = words;
      }
      all() {
        const output = this.words?.length ? `$${this.words.join("$")}$` : "No input";
        console.log(output)
      };
    }
    
    var x = new Add("hehe", "hoho", "haha", "hihi", "huhu");
    var y = new Add("this", "is", "awesome");
    var z = new Add("lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit");
    var nope = new Add()
    x.all();
    y.all();
    z.all();
    nope.all();