Home > OS >  Make a text encoder
Make a text encoder

Time:11-19

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$

CodePudding user response:

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();

CodePudding user response:

You seem to have a problem with the concept of arrays (your variable this.words is an array). You might want to look into arrays and iteration before doing anything else.

Here are a couple of links that might help:

MDN Arrays
MDN loops and iterations

Basically if you want to do something with the values of an array you should learn to do it with a for loop, which is a way of going through (iterating over) each of the values contained in the array and doing a specific action with those values.

I know there are actually many ways of doing this (using join is one of them), but I would recommend you try and understand the basics first.

An example of your code with a for loop would look something like this:

class Add {
  constructor(...words) {
    this.words = words;
  }
  all() {
    let newString = "";
    for (let word of this.words) {
      newString  = "$"   word;
    }
    console.log(newString   "$");
  }
}

var x = new Add("hehe", "hoho", "haha", "hihi", "huhu");

x.all();

  • Related