Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eftakhairul/e4084ecae762653a9c6f4b61bb433061 to your computer and use it in GitHub Desktop.
Save eftakhairul/e4084ecae762653a9c6f4b61bb433061 to your computer and use it in GitHub Desktop.
In-class practice problem
/**
* Account class (Parent class)
* @constructor
*/
var Account = function() {
this.amount = 0;
this.setAmount = function(amount) {
this.amount = amount;
}
this.getAmount = function() {
return this.amount;
}
};
/**
* CheckingAccount class (First child class)
* @constructor
* @param {int} amount - The initial amount when you open the checking account
*/
var CheckingAccount = function(amount) {
this.setAmount(amount);
this.withdraw = function(amount) {
var updatedAmount = this.getAmount() - amount;
if (updatedAmount < 0) {
throw new Error("Amount can't be negetive");
}
this.setAmount(updatedAmount);
return this.getAmount();
}
this.deposit = function(amount) {
this.setAmount(amount);
}
}
//inheritance
CheckingAccount.prototype = new Account();
/**
* SavingAccount class (Second child class)
* @constructor
* @param {int} amount - The initial amount when you open the saving account
*/
var SavingAccount = function(amount) {
this.setAmount(amount);
this.withdraw= function(amount) {
var updatedAmount = this.getAmount() - amount;
if (updatedAmount < 0) {
throw new Error("Amount can't be negetive");
} else if(updatedAmount < 500) {
throw new Error("Amount can't be less than 500");
}
this.setAmount(updatedAmount);
return this.getAmount();
}
this.deposit = function(amount) {
this.setAmount(amount);
}
}
//inheritance
SavingAccount.prototype = new Account();
//Test Case -- 1
var checkingAccont1 = new CheckingAccount(1000);
console.log("Balance: ", checkingAccont1.getAmount());
//Withdraw 100
checkingAccont1.withdraw(100);
try{
//Withdraw balance more than available balance
checkingAccont1.withdraw(10000);
} catch (e) {
console.log('error catched for negetive balance');
console.log('everything is okay for checking');
}
//Test Case -- 2
var savingAccont1 = new SavingAccount(1000);
console.log("Balance: ", savingAccont1.getAmount());
//Withdraw 100
savingAccont1.withdraw(100);
try{
//Withdraw balance more than available balance
savingAccont1.withdraw(500);
} catch (e) {
console.log('error catched for less than 500');
console.log('everything is okay for saving account');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment