Last active
August 29, 2015 14:16
-
-
Save hexadeciman/6fc0172f3d41af1d490b to your computer and use it in GitHub Desktop.
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
'use strict'; | |
function ChangeMachine() { | |
var coins = { | |
'75p' : 75, | |
'15p' : 15, | |
'3p' : 3, | |
'1p' : 1, | |
'1/2p' : 0.5, | |
'1/4p' : 0.25 | |
} | |
var convertPoundsToPennies = function(pounds) { | |
return pounds * 100; | |
}; | |
var inputVerification = function(price, payed) { | |
if (typeof price !== 'number' || typeof payed !== 'number') { | |
throw 'please enter a number'; | |
} else if (price > payed) { | |
throw 'not enough payed'; | |
} else if (price * 100 < 0.25) { | |
throw 'enter a higher price'; | |
} else if (price == payed) { | |
throw 'no change needed'; | |
} else if (price <= 0 || payed <= 0) { | |
throw 'This is not a correct price'; | |
} | |
return false; | |
}; | |
this.returnChange = function(pricePounds, payedPounds) { | |
var error; | |
var changeObject = []; | |
var totalChange; | |
var price = convertPoundsToPennies(pricePounds); | |
var payed = convertPoundsToPennies(payedPounds); | |
try { | |
error = inputVerification(price, payed); | |
if (!error) { | |
totalChange = payed - price; | |
var coinNames; | |
for (coinNames in coins) { | |
if (coins.hasOwnProperty(coinNames)) { | |
var coinValue = coins[coinNames]; | |
var coinsCount = parseInt((totalChange / coinValue), 10); | |
if (coinsCount >= 1) { | |
changeObject.push({ | |
name : coinNames, | |
n : coinsCount | |
}); | |
} | |
//how much change is left over | |
totalChange = totalChange % coinValue; | |
} | |
} | |
return changeObject; | |
} | |
}catch (error) { | |
console.log(error); | |
return false; | |
} | |
}; | |
} | |
var pricePounds = 1; | |
var payedPounds = 2; | |
var machine = new ChangeMachine(); | |
var change = machine.returnChange(pricePounds, payedPounds); | |
console.log(change); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment