How to take the values of the property of an object created with a constructor function and group in an array?

Asked

Viewed 62 times

1

I have these two construction functions that should create three passengers and a wagon and I need to create a method that when a passenger is added to the wagon he adds his name to the Passenger array of the wagon and decreases the capacity by 1.
I’ve already made the method decrease the capacity, but I can’t get the names of the passengers. I could take the names of the three walkers created and push the array, but I would have a way to make any name created with that constructor add to the array.

function Traveler(name) {
    this.name = name;
    this.food = 1;
    this.isHealthy = true;
}

function Wagon(capacity) {
    this.capacity = capacity;
    this.passengers = [];
}

1 answer

0


You can get the passenger name by accessing the property value name of each passenger body.

Adding a passenger, just decrease the capacity of the cart.

This can be done by adding a method to this class using prototypes

function Traveller(name) {
    this.name = name;
    this.food = 1;
    this.isHealthy = true;
}

function Wagon(capacity) {
    this.capacity = capacity;
    this.passengers = [];
}

Wagon.prototype.addTraveller = function (traveller) {
    if (this.capacity === 0) {
      return document.write(`<p>Essa carroça não tem mais capacidade, passageiro ${traveller.name} não foi adicionado.</p>`);
    }
    this.passengers.push(traveller.name);
    this.capacity--;
    document.write(`<p>Adicionado passageiro ${traveller.name}<p>`);
}

Wagon.prototype.removeTraveller = function (traveller) {
    let index = this.passengers.findIndex((v) => v === traveller.name);
    if (index < 0) {
      document.write(`<p>Passageiro ${traveller.name} não estava na carroça, portanto não foi removido<p>`);
      return
    }
    
    this.passengers.splice(index, 1);
    this.capacity++;
    document.write(`<p>Removido passageiro ${traveller.name}<p>`);
}

Wagon.prototype.output = function () {
  document.write(`<p>Capacidade: ${this.capacity} - ${JSON.stringify(this.passengers)}</p>`);
}

const wagon = new Wagon(3);
const traveller1 = new Traveller('Jon');
const traveller2 = new Traveller('Arya');
const traveller3 = new Traveller('Daenerys');
const traveller4 = new Traveller('Ned');
const traveller5 = new Traveller('Tyrion');

wagon.output();

wagon.addTraveller(traveller1);
wagon.output();

wagon.addTraveller(traveller2);
wagon.output();

wagon.addTraveller(traveller3);
wagon.output();


wagon.removeTraveller(traveller4);
wagon.output();

wagon.removeTraveller(traveller3);
wagon.output();

wagon.addTraveller(traveller4);
wagon.output();

wagon.addTraveller(traveller5);
wagon.output();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.