A bank account class

Write a class Account that keeps its balance private, and follow the commands in the input.

What to build

A class whose balance can change only through its own methods.

Requirements

  • The account starts at 0, and the balance is in a private field.
  • deposit N: add N and print deposited N.
  • withdraw N: if N is more than the balance, print insufficient funds and change nothing. Otherwise take it out and print withdrew N.
  • balance: print balance N.

Input

Several lines, each a command.

Output

One line per command.

Constraints

There are from 1 to 100 commands. Every N is a whole number from 1 to 1000000.

Example

Input:

deposit 100
withdraw 30
balance

Output:

deposited 100
withdrew 30
balance 70

Why it works

Because #balance cannot be touched from outside, the rule against overdrawing lives in one place and cannot be bypassed. A getter makes reading the balance look like reading a property.

Examples

Example 1 · Input
deposit 100
withdraw 30
balance
Expected output
deposited 100
withdrew 30
balance 70
Example 2 · Input
withdraw 5
balance
Expected output
insufficient funds
balance 0

Hints

Hint 1

class Account with a private field #balance = 0, and methods deposit(amount), withdraw(amount) and a getter balance.

Hint 2

withdraw should refuse (return false) when amount is more than the balance.

Hint 3

Read lines until prompt() gives null; Number(parts[1]) is the amount.

Solution

Show one correct solution (try it yourself first)
class Account {
  #balance = 0;
  deposit(amount) {
    this.#balance += amount;
  }
  withdraw(amount) {
    if (amount > this.#balance) return false;
    this.#balance -= amount;
    return true;
  }
  get balance() {
    return this.#balance;
  }
}

const account = new Account();
let line = prompt();
while (line !== null) {
  const [command, text] = line.split(" ");
  const amount = Number(text);
  if (command === "deposit") {
    account.deposit(amount);
    console.log(`deposited ${amount}`);
  } else if (command === "withdraw") {
    console.log(account.withdraw(amount) ? `withdrew ${amount}` : "insufficient funds");
  } else {
    console.log(`balance ${account.balance}`);
  }
  line = prompt();
}

Lesson: Classes and prototypes →