'use strict'; // ⭐ toggle sloppy/strict mode
const { log } = console;
// bank account
function BankAccount(initialBalance = 0) {
// ⭐ initial balance
let balance = initialBalance;
// ⭐ return an object
return {
getBalance() {
return balance
},
deposit(amount) {
balance += amount;
return balance;
},
withdraw(amount) {
// check if we have enough money to withdraw.
if (amount > balance) {
log(`❗ balance: $${balance} less than withdraw amount: $${amount}.`);
return false; // withdraw failed
}
balance -= amount;
return true; // withdraw successful
}
}
}
const myAccount = BankAccount(100); // initial balance = 100
// log
[
myAccount.deposit(10), // 110
myAccount.withdraw(80), // true (successful)
myAccount.getBalance(), // 30
myAccount.withdraw(80), // false (failed)
// ❗ balance (30) is less then withdraw amount (80).
myAccount.getBalance(), // 39
].forEach(x => log(x));