Setters: throwing an error based on number length

Viewed 19

i have here a little test with a class object. i'm making some personal information for our dear friend Sauron. However, Sauron let me know that i used his wrong telephone number, he is rather cross with me.

Needless to say i was persuaded to change this number to the correct one very quickly. I also wanted to give him the option to change it himself in the future, so i used a setter, that would throw an error if he tried to enter more or less than 8 digits.

However, it seems that the number gets updated no matter what the dark lord enter as a phone number.

I can't seem to get the setter to throw and error when just three digits are entered, or anyhting that is not exactly 8. It just updates the number regardless.

Please help me evade the wrath of Mordor.

yours truly,

Thomas

class Contact {
  constructor(name, lastname, adress = {}, telefoonNr) {
    this.name = name;
    this.lastname = lastname;
    this.adress = adress;
    this.telefoonNr = telefoonNr;
  }
  get fullName() {
    return `${this.name} ${this.lastname}`;
  }
  set fullName(value) {
    const parts = value.split(' ');
    this.name = parts[0];
    this.lastname = parts[1];
  }

  set updatePhoneNr(value) {
    if (value.toString().length > 8) {
      throw 'error, Number is too long';
    } else if (value.toString().length > 8) {
      throw 'error, Number is too short';
    } else {
      this.telefoonNr = value;
      console.log('Phone number has been updated')
    }
  }
}


const sauron = new Contact(
  'Sauron',
  'Sauronson', {
    'street': 'Barad-dur',
    'houseNr': 1,
    'postalCode': '0001 RI',
    'city': 'Mordor'
  },
  11291100
)

console.log(sauron);

try {
  sauron.updatePhoneNr = 71000;
} catch (error) {
  console.error(error, ' That is not a valid telephone number');
}

console.log(sauron);

0 Answers
Related