Skip to content

Instantly share code, notes, and snippets.

@aamirsahmad
Created August 10, 2018 19:34
Show Gist options
  • Save aamirsahmad/d9122b40443ab27a8d27864ee88fae94 to your computer and use it in GitHub Desktop.
Save aamirsahmad/d9122b40443ab27a8d27864ee88fae94 to your computer and use it in GitHub Desktop.
A simple BankAccount implementation that uses composability and FP concepts in ES2017
// Factory function
const createBankAccount = (balance = 0, type = 'CHECKING') => ({balance, type})
// Helper
const checkIfNegative = x => {
if (x < 0)
throw Error('Value can not be negative')
return x
}
const checkIfEnoughFunds = (ba, amt) => {
if (amt > ba.balance)
throw Error('Not enough funds')
return amt
}
const deposit = (bankAccount) => (amount) => bankAccount.balance += checkIfNegative(amount)
const withdraw = (bankAccount) => (amount) => bankAccount.balance -= checkIfEnoughFunds(bankAccount, checkIfNegative(amount))
module.exports = {
createBankAccount,
deposit,
withdraw,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment