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 should use
find
instead:If there was no customer found, it returns
undefined
and you can check for that.