js exercise bank account constructor functions and prototypes solution

Solutions on MaxInterview for js exercise bank account constructor functions and prototypes solution by the best coders in the world

showing results for - "js exercise bank account constructor functions and prototypes solution"
Marc
11 Aug 2016
1function Account(name, balance) {
2  this.name = name;
3  this.balance = balance;
4}
5
6Account.prototype.deposit = function(amount) {
7  if (this._isPositive(amount)) {
8    this.balance += amount;
9    console.info(`Deposit: ${this.name} new balance is ${this.balance}`);
10    return true;
11  }
12  return false;
13}
14
15Account.prototype.withdraw = function(amount) {
16  if (this._isAllowed(amount)) {
17    this.balance -= amount;
18    console.info(`Withdraw: ${this.name} new balance is ${this.balance}`);
19    return true;
20  }
21  return false;
22}
23
24Account.prototype.transfer = function(amount, account) {
25  if (this.withdraw(amount) && account.deposit(amount)) {
26    console.info(`Transfer: ${amount} has been moved from ${this.name} to ${account.name}`);
27    return true;
28  }
29  return false;
30}
31
32
33Account.prototype._isPositive = function(amount) {
34  const isPositive = amount > 0;
35  if (!isPositive) {
36    console.error('Amount must be positive!');
37    return false;
38  }
39  return true;
40}
41
42Account.prototype._isAllowed = function(amount) {
43  if (!this._isPositive(amount)) return false;
44
45  const isAllowed = this.balance - amount >= 0;
46  if (!isAllowed) {
47    console.error('You have insufficent funds!');
48    return false;
49  }
50  return true;
51}
52
53const a = new Account('a', 100);
54const b = new Account('b', 0);
55
56
57output.innerText += `before:  a: ${a.balance}, b: ${b.balance}\n`;
58
59a.transfer(100, b);
60
61output.innerText += `after:  a: ${a.balance}, b: ${b.balance}\n`;