1

I create UrlParamClass and i want to know, how i can append value. See this example:

class UrlParam {
    append = (key, value) => {
        return `&${key}=${value}`
    }
}

let param = new UrlParam()

param.append('module','clothes')
param.append('module','shoes')
param.append('module','gloves')


console.log(param) //i want to see: &module=clothes&module=shoes&module=gloves
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Marty
  • 534
  • 8
  • 24
  • 2
    You aren't *doing* anything with the result of the function, least of all storing it in the object, and neither do you have a `toString` method that would give you what you want. – Niet the Dark Absol Oct 11 '18 at 09:30

2 Answers2

1

If you are using a Class, what you can do is to use an inner instance attributein your class.

Initialize it in your constructor and keep changing it in your append method:

class UrlParam {
  constructor(value) {
    this.value = value;
  }
  append(key, value){
    this.value += `&${key}=${value}`
  }
}

let param = new UrlParam('');

param.append('module', 'clothes')
param.append('module', 'shoes')
param.append('module', 'gloves')


console.log(param) //i want to see: &module=clothes&module=shoes&module=gloves
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

If you're going to write a class, I'd go for this approach :

  • First, initialize your object with an empty params array
  • Then, feed the instance's array within the append method
  • Lastly, write a toString method that will "glue" the params together with the expected syntax

class UrlParam {
    constructor() {
        this.params = [];
    }

    append(key, value) {
        this.params.push({key, value});
    }

    toString() {
        return this.params
            .map(({key, value}) => `&${key}=${value}`)
            .join('');
    }
}

let param = new UrlParam();
param.append('module', 'clothes')
param.append('module', 'shoes')
param.append('module', 'gloves')

console.log(param.toString());
Logar
  • 1,248
  • 9
  • 17