Factory Method
// (a) Account Factory + (d) Initializing Fields + (b) Additional Fields
export const Account = (account_number, date_created, currency) => {
// (d) All fields below and above are not exposed publicly
let balance = 0;
const debit = (amount) => {
if (amount < 0) { throw new Error(`Illegal amount.`); }
if (balance < amount) { throw new Error(`Insufficient account balance.`); }
balance -= amount;
return balance;
};
const credit = (amount) => {
if (amount < 0) { throw new Error(`Illegal amount.`); }
balance += amount;
return balance;
}
// (e) Logging all fields and returning them as an object.
const info = () => {
console.log(`Account [${account_number}]: ${balance}${currency} (${date_created})`)
return { account_number, date_created, currency, balance };
}
// (c) Fields from "b" and "balance" are out of scope
return { debit, credit, info };
};
export default Account;