Created
August 10, 2018 19:34
-
-
Save aamirsahmad/d9122b40443ab27a8d27864ee88fae94 to your computer and use it in GitHub Desktop.
A simple BankAccount implementation that uses composability and FP concepts in ES2017
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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