Home > Back-end >  How to include a history of all the names in the setName method and then get all the names
How to include a history of all the names in the setName method and then get all the names

Time:10-16

I attempted to use the push method on an array for the setNames but the array just prints out whichever name the cat is set to. The new name doesn't append to the old one

Below is what I am having issues with:

  • Change the setName() method to create a list of all the previous names the cat has had
  • Create a getNames() method to return the list of all the names the cat has had
class Cat {
  constructor(name) {

    this.name = name
  }

  getName() {
    return this.name
  }
  
  setName(name) {
    this.name = name
    // Not sure if below two lines are correct
    let nameArr = [];
    nameArr.push(name)
    console.log(nameArr)
  }

  getNames() {
    return
  }
}

let cat = new Cat();

cat.setName("Flash");
cat.setName("Sophie");

// prints ["Flash"] and ["Sophie"] separately
// But I want it to look like this: ["Flash", "Sophie"]

CodePudding user response:

You seamed to be at the beginning of a great developer career, and even thought the answer is very simple, I will use it to give you some guidelines how to approach problem-solving.

Try always to resolve your problem with the "pen and paper", meaning the first thing is to understand the problem and resolve it manually. Only then you can pour it into a programming code.

First, the strict solution to your original posted question:

class Cat {
  names = [];

  constructor(name) {
    if (name) this.setName(name);
  }

  setName(name) {
    this.names.push(name);
    console.log(this.names);
  }
}


let cat = new Cat();

cat.setName("Flash");    // prints ["Flash"]
cat.setName("Sophie");   // prints ["Flash", "Sophie"]

And now some proposals how to improve the solution. I assume every cat has a name and the name is strictly only the last name given. Hence, the previous names should be kept separately. A method to get all names will be added (as requested by the title of your question).

class Cat {
  previousNames = [];

  constructor(name) {
    if (!name) throw Error('I need a name to exist.');
    this.setName(name);
  }

  setName(name) {
    this.rememberPreviousName(this.name);
    this.name = name;
  }

  rememberPreviousName(name) {
    if (name) this.previousNames.push(name);
  }
  getAllNames() {
    return [...this.previousNames, this.name];
  }
}


let cat = new Cat("Flash");
console.log("Cat's name:", cat.name);
// prints "Cat's name: Flash"
cat.setName("Sophie");
console.log("Cat's name:", cat.name);
// prints "Cat's name: Sophie"
console.log("Cat's previous names:", cat.previousNames);
// prints "Cat's previous names: ["Flash"]"
console.log("Cat's all names:", cat.getAllNames());
// prints "Cat's all names: ["Flash", "Sophie"]"

Hope it helps you a bit

  • Related