Code Lab

Modo entrevista. Cronômetro de 20 min, sem dicas e sem autocompletar

Bank account and savings account

DifícilClasses20 min

Write a class BankAccount and its subclass SavingsAccount.

BankAccount:

  • Constructor: new BankAccount(owner, balance). owner is a string, balance is a number that is 0 or more. If balance is not passed, it is 0.
  • A getter owner returns the owner, a getter balance returns the current balance.
  • There is no setter for balance: account.balance = 500 must not change the balance. Only deposit and withdraw change it.
  • The method deposit(amount) adds amount to the balance and returns the new balance.
  • withdraw(amount) takes amount from the balance and returns the new balance. You can take the whole balance (the result is 0). If amount is greater than the balance, throw new Error('Insufficient funds'). It is a plain Error object, not a RangeError and not a string.
  • If amount is 0 or negative, deposit and withdraw throw a RangeError (any message).
  • When a method throws, the balance stays the same.

SavingsAccount:

  • It inherits from BankAccount with extends. Constructor: new SavingsAccount(owner, balance, rate), where rate is a percent, 0 or more (for example 5 means 5%). Call the parent constructor with super.
  • owner, balance, deposit and withdraw come from BankAccount. Do not write them again in SavingsAccount.
  • addInterest() adds balance * rate / 100 to the balance (not rounded) and returns the new balance. If this interest is 0 (rate 0 or balance 0), the balance stays the same and there is no error.

Every account keeps its own balance: a change in one account does not change another.

Exemplos

new BankAccount('Ann', 100).deposit(50)

Retorna 150

new BankAccount('Bob').balance

Retorna 0

new SavingsAccount('Kate', 1000, 5).addInterest()

Retorna 1050

Fonte

Carregando o editor...
  1. The constructor stores the owner and the balance, the default balance is 0
  2. deposit and withdraw return the new balance
  3. Taking more than the balance throws Insufficient funds
  4. SavingsAccount is a BankAccount and adds interest

Os testes ocultos rodam no envio