Javascript: Add player to a specific object in an array - javascript

I'm making an application where a user can create a team and add players to it, to track team stats.
In my code, I have an array of teams, a function to create a team and a function to create a player.
I want createNewPlayer() to accept a team variable, so it adds the player to the wright team.
Now, the function returns the "Team does not exist", while I created a team with that exact name before running the function.
Any idea how to fix this problem?
const Teams = []
// Team Class
class Team {
constructor(name, players) {
this.name = name;
this.players = [];
}
}
// Player class
class Player {
constructor(name, lastName, team, goal, assist, yellowCard, redCard, minPlayed) {
this.name = name;
this.lastName = lastName;
this.team = team;
this.goal = 0;
this.assist = 0;
this.yellowCard = 0;
this.redCard = 0;
this.minPlayed = 0;
}
}
// Create new team
const createNewTeam = (name) => {
if (typeof name === "string") {
let newTeam = new Team(name);
Teams.push(newTeam);
} else {
console.log("Something went wrong.");
}
}
//Create new player
const createNewPlayer = (name, lastName, team) => {
let newPlayer = new Player(name, lastName, team);
for (i = 0; i < Teams.length; i++) {
if (Teams[i].name === team) {
Teams[i].players.push(newPlayer);
} else {
console.log("Team does not exist!")
}
}
}

You loop over all the teams, and in every iteration in which the team name does not match, you log the error.
You should try something like this:
let teamFound = false;
for (i = 0; i < Teams.length; i++) {
if (Teams[i].name === team) {
Teams[i].players.push(newPlayer);
teamFound = true;
break;
}
}
if (!teamFound) {
console.log("Team does not exist!")
}

I think you have to check for Teams[i].name == team.name instead.

I would try something like this:
const createNewPlayer = (name, lastName, teamName) => {
let newPlayer = new Player(name, lastName, teamName);
let team = Teams.find((Team) => Team.name === teamName)
if(team !== undefined) {
team.players.push
} else {
console.log("Team does not exist!")
}
return newPlayer
}

Related

JavaScript Need help writing shouldQuarantine prototype

Need this to determine if any of the passengers are isHealthy =false then quarantine the wagon. I may have an issue on the join prototype as well. The isHealthy is only triggered if they eat and have no food. So it is possible for them to eat, and then have no food but not trigger isHealthy.
I am very new to this please be patient.
const Traveler = function (travelerName) {
this.name = travelerName;
this.food = 1;
this.isHealthy = true;
};
Traveler.prototype.hunt = function () {
this.food += 2;
console.log(this.food);
};
Traveler.prototype.eat = function () {
this.food -= 1;
if (this.food === 1) {
} else {
this.food === 0;
this.isHealthy = false;
}
console.log(this.food);
};
console.log(new Traveler("John"));
function Wagon(capacity) {
this.capacity = capacity;
this.passengers = [];
}
console.log(new Wagon(4));
Wagon.prototype.getAvailableSeatCount = function () {
let seatingCapacity = this.capacity - this.passengers.length;
console.log(seatingCapacity);
return seatingCapacity;
};
Wagon.prototype.join = function (traveler) {
console.log(this.capacity);
let currentCapacity = this.capacity;
if (currentCapacity <= this.passengers.length) {
this.currentCapacity = 0;
} else if (this.getAvailableSeatCount != 0) {
this.passengers.push(traveler);
}
console.log(this.passengers);
};
Wagon.prototype.shouldQuarantine = function () {
for (let i = 0; i < this.passengers.length; i++) {
if (this.passengers[i].isHealthy) {
return false;
}
}
};
Wagon.prototype.totalFood = function () {
let totalFood = "";
this.passengers.forEach(this.food);
console.log(this.food);
};
In you eat method of the Traveler class, first check if there is any food. If there is, then subtract one and check if the food is now empty. If it is then set isHealthy to false.
Traveler.prototype.eat = function () {
if (this.food > 0) {
this.food -= 1;
if (this.food === 0) {
this.isHealthy = false;
}
}
};
Subsequently you should also modify your hunt method to make your traveler healthy again after hunting.
Traveler.prototype.hunt = function () {
this.food += 2;
this.isHealthy = true;
};
In the shouldQuarantine method of the Wagon class, instead of checking if all passengers are healthy, check if anyone of them is not healthy and return true if that is the case.
If everyone is healthy, the loop will finish. Return false after the loop.
Wagon.prototype.shouldQuarantine = function () {
for (let i = 0; i < this.passengers.length; i++) {
if (!this.passengers[i].isHealthy) {
return true;
}
}
return false;
};
Alternatively you could use the some method on the this.passengers array to check if any of the passenger isn't healthy.
Wagon.prototype.shouldQuarantine = function () {
return this.passengers.some(
passenger => passenger.isHealthy === false
);
};
The join method can be simplyfied. You only need the result from this.getAvailableSeatCount() to see if there is any room. Add the traveler if the result is not 0.
Wagon.prototype.join = function (traveler) {
const availableSeats = this.getAvailableSeatCount();
if (availableSeats !== 0) {
this.passengers.push(traveler);
}
};
I also noticed that the totalFood method doesn't work as expected, but I'll let this one up to you. Hint: totalFood should be a number. Loop over every passenger and add the amount of food to the totalFood value.

The value returned for a newly constructed object returns the value of the previously created one

I have the following challenge for practicing OOP in javascript:
The Bank should allow us to:
Add customers
A customer should be able to deposit an amount.
A customer should bevable to withdraw an amount.
A customer should be able see his/her
account.
So I did the following, I created a Bank class with different methods.
It seems to work fine with 1 person, but my problem is once I add a new customer, and run the methods on the new customer it returns the value of the first customer.
class Bank {
constructor() {
this.customers = [];
}
addCustomer(customer) {
this.customers.push({ name: customer, account: 0 });
}
printAccount(customer) {
if (this.customers.some((person, idx) => person.name === customer)) {
console.log(
`${this.customers[0].name}'s account is ${this.customers[0].account}`
);
} else {
console.log("no access");
}
}
depositAmount(customer, amount) {
if (this.customers.some(person => person.name === customer)) {
this.customers[0].account += amount;
} else {
return;
}
}
withdrawAmount(customer, amount) {
if (this.customers.some(person => person.name === customer)) {
this.customers[0].account -= amount;
} else {
return;
}
}
}
const bank = new Bank();
bank.addCustomer("daniel");
bank.depositAmount("daniel", 10);
bank.withdrawAmount("daniel", 5);
bank.printAccount("daniel");
bank.addCustomer("gwen");
bank.depositAmount("gwen", 10);
bank.printAccount("gwen");
console.log(bank);
You're always using this.customers[0] in your methods, so it always operates on the first customer.
Use find() to find the customer object, and use that.
class Bank {
constructor() {
this.customers = [];
}
addCustomer(customer) {
this.customers.push({
name: customer,
account: 0
});
}
getCustomer(name) {
return this.customers.find(person => person.name == name);
}
printAccount(name) {
const customer = this.getCustomer(name);
if (customer) {
console.log(
`${customer.name}'s account is ${customer.account}`
);
} else {
console.log("no access");
}
}
depositAmount(name, amount) {
const customer = this.getCustomer(name);
if (customer) {
customer.account += amount;
}
}
withdrawAmount(name, amount) {
this.depositAmount(name, -amount);
}
}
const bank = new Bank();
bank.addCustomer("daniel");
bank.depositAmount("daniel", 10);
bank.withdrawAmount("daniel", 5);
bank.printAccount("daniel");
bank.addCustomer("gwen");
bank.depositAmount("gwen", 10);
bank.printAccount("gwen");
console.log(bank);
You should use find instead:
depositAmount(customer, amount) {
const customer = this.customers.find((person) => person.name === customer);
if (!customer) return; // no customer exists
customer.account += amount; // add to customer
}
If there was no customer found, it returns undefined and you can check for that.

Trying to return just the description in an array of instances of a class

So this is what I am trying to solve:
class ViewRole {
name
description
constructor(name, description) {
this.name = name;
this.description = description;
}
}
class NewRole {
name;
description;
constructor(name, description) {
this.name = name;
this.description = description;
}
}
var armadilloRoles = [
new NewRole('Billing', 'armadillo.organization.billing'),
new NewRole('Doctor', 'armadillo.organization.doctor'),
new NewRole('Nurse Practitioner', 'armadillo.organization.nursePractitioner'),
new NewRole('Patient', 'armadillo.microurb.billing'),
new NewRole('Microurb admin', 'armadillo.organization.admin'),
new NewRole('Microurb admin', 'armadillo.organization.admin'),
new NewRole('Microurb billing', 'armadillo.organization.billing'),
new NewRole('Respiratory therapist', 'armadillo.microurb.respiratoryTherapist'),
new NewRole('Microurb commercial contact', 'armadillo.microurb.practiceGrowthDirector')
];
var viewRoles = [];
for (var i = 0; i < armadilloRoles.length; i++) {
const role = armadilloRoles[i];
const viewRoleDto = new ViewRole(role.name, role.description);
// if (viewRoleDto[i].description.startsWith('armadillo.organization.')) {
// viewRoles.push(viewRoleDto[i]);
// }
viewRoles.push(viewRole);
}
console.log(viewRoles);
I have tried a variety of ways of implementing an if conditional with a startsWith() method.
I want to return just the ones that have armadillo.organization. as the description.
A good way would be to use reduce like this:
const matches = armadilloRoles.reduce(
(prev, cur) =>
cur.description.startsWith("armadillo.organization") ? [...prev, cur] : prev,
[]
);

Remove all Groups and children in a nodeJS app

i need help with my little nodeJS app. i need to create a function which will delete nested groups in a tree.
iv'e debugged my tree search recursion and it works great.
but my delete function not deleting anything.
i need to get to the parent and delete it from the array.
tree looks like that:
class Group {
constructor(name, parent) {
this.name = name;
this.parent = parent || null;
this.children = [];
this.users = new users || null;
}
}
class groups {
constructor() {
this.root = new Group('root');
}
}
working tree search function (feel free to use!)
and non functioning delete function
findGroupByName(name) {
if (!name)
return null;
return this._findGroupByNameInternal(this.root, name);
}
_findGroupByNameInternal(group, name) {
if (!group)
return null;
if (group.name === name)
return group;
for (const g of group.children) {
const result = this._findGroupByNameInternal(g, name);
if (!result)
continue;
return result;
}
}
removeByName(name) {
if (!this.children)
return;
const groupToRemove = this.findGroupByName(name);
if (groupToRemove) {
this.children = this.children.filter(g => g !== groupToRemove);
}
}
menu handler
function removeGroup(callback) { //need fixing
rl.question('Enter group name to delete: \n', (groupName) => {
let parentGroup = programdata.groups.findGroupByName(groupName);
programdata.groups.removeByName(groupName)
console.log(parentGroup);
callback()
})
}
function showGroups(callback) {
callback()
}
This isn't working for you because the group returned by _findGroupByNameInternal() isn't necessarily a child of the instance you called removeByName() on. So when you try to filter() the instance children, it may not be there — it may be a grandchild or deeper. You need to remove the group when you find it and still know the parent. There's a lot of way to do that, but here's a simple one:
class Groups {
constructor() {
this.root = new Group('root');
}
removeByName(name){
this.root.removeByName(name)
}
}
class Group {
constructor(name, parent) {
this.name = name;
this.parent = parent || null;
this.children = [];
}
removeByName(name){
// is name in children?
let index = this.children.findIndex(g => g.name === name)
if (index > -1) {
// delete it
this.children.splice(index, 1)
console.log(`removed ${name} from ${this.name}`)
} else {
// otherwise recurse on children
this.children.forEach(child => child.removeByName(name))
}
}
}
Here's a full snippet:
class Group {
constructor(name, parent) {
this.name = name;
this.parent = parent || null;
this.children = [];
}
removeByName(name){
let index = this.children.findIndex(g => g.name === name)
if (index > -1) {
this.children.splice(index, 1)
console.log(`removed ${name} from ${this.name}`)
} else {
this.children.forEach(child => child.removeByName(name))
}
}
}
class Groups {
constructor() {
this.root = new Group('root');
}
removeByName(name){
this.root.removeByName(name)
}
}
let groups = new Groups()
// Make some nested groups
for (let j=0; j < 5; j++){
let parent = groups.root
let group = new Group(`group_${j}`, parent )
parent.children.push(group)
parent = group
for (let i=0; i < 5; i++){
let group = new Group(`group_${j}_${i}`, parent )
parent.children.push(group)
}
}
// Delete the second second of group 3 (group_3_1)
groups.removeByName('group_3_1')
// Make sure group_3_1 is gone
console.log(groups.root.children[3].children.map(c => c.name))

create objects using factory in Javascript

I'm having trying to create two objects of type person using factory and on the first try I create the first element and the second attempt instead of creating the second element creates a new element but with the same characteristics as the first element
class Person
function Person(id, name) {
this.id = id;
this.name = name;
}
class Student extends Person
function Student(id, name) {
Person.call(this, id, name);
}
class Teacher extends Person
function Teacher(id, name) {
Person.call(this, id, name);
}
using function factory to create student and teacher
function Factory() {
this.createPerson = function(type, name) {
var person;
var idStudent = 0;
var idTeacher = 0;
switch (type) {
case "1":
person = new Student(idStudent++, name);
break;
case "2":
person = new Teacher(idTeacher++, name);
break;
}
return person;
}
}
class School has an array of person
function School(id) {
this.persons = [];
this.factory = new Factory();
this.personCreate = null;
this.createStudentAndTeacher = function() {
var type = prompt("Choose ? \n\n[1-Student | 2-Teacher ]");
var name = prompt("Write name?");
if (type !== null) {
this.personCreate = this.factory.createPerson(type,name);
this.persons.push(this.personCreate);
} else {
alert("need to choose");
}
}
}
created by default
var s = new School(1);
var btn = document.createElement('button');
btn.value = "create";
btn.onclick = function(){
s.createStudentAndTeacher();
}
my doubt is when I create the Student object with name "John", return student.id = 0 and student.name = John but when I create the new Student object with name "Elisa", return the same information student.id = 0 and student.name = John and in fact, should return student.id = 1 and student.name = Elisa and if I create new Teacher object with name "Jerry", return the same information student.id = 0 and student.name = John and in fact, should return teacher.id = 0 and teacher.name = Jerry
what I´m doing wrong?
The code has a bug. In the Factory definition, change this
function Factory() {
this.createPerson = function(type, name) {
var person;
var idStudent = 0;
var idTeacher = 0;
to this
function Factory() {
var idStudent = 0;
var idTeacher = 0;
this.createPerson = function(type, name) {
var person;
then use the console, run these lines.
var s = new School();
s.createStudentAndTeacher(); // john
s.createStudentAndTeacher(); // bob
s.persons[0] // id 0:john
s.persons[1] // id 1:bob
Your createPerson is redeclaring idStudent and idTeacher (and resetting them to 0). Try moving that code out of that block.

Categories

Resources