Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overwrite empty string in Javascript object

I need that child class StringBuilder would pass the string to the parent class and call the minus method. The following code does not work unless I won’t hardcode the string in the constructor. With numbers this works just fine. Why doesn’t it overwrite the string? Or maybe I’m doing everything completely wrong?

class Builder {
    constructor() {
        this.int = 0
        this.str = ''
    }

    minus(...n) {
        this.int = n.reduce((sum, current) => sum - current, this.int)
        this.str = this.str.slice(0, -n)
        return this
    }
}

class IntBuilder extends Builder {
    constructor(int) {
        super(int)
    }
}

class StringBuilder extends Builder {
    constructor(str) {
        super(str)
    }
}

let number = new IntBuilder()
number.minus(100, 99)

console.log(number)

let string = new StringBuilder('Hello')

string.minus(2)

console.log(string)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your Builder constructor does not take any parameters. Declare a parameter and assign that parameter to this.str. You can use default parameters to ensure it will be initialized to whatever you want even when the constructor is called without parameters.

class Builder {
  constructor(str = "") {
    this.int = 0
    this.str = str
  }

  minus(...n) {
    this.int = n.reduce((sum, current) => sum - current, this.int)
    this.str = this.str.slice(0, -n);
    return this;
  }
}

class IntBuilder extends Builder {
  constructor(int) {
    super(int)
  }
}

class StringBuilder extends Builder {
  constructor(str) {
    super(str)
  }
}

let number = new IntBuilder()
number.minus(100, 99)

console.log(number)

let string = new StringBuilder('Hello')

string.minus(2)

console.log(string)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading