Skip to content

Instantly share code, notes, and snippets.

@hexadeciman
Last active August 29, 2015 14:16
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 hexadeciman/6fc0172f3d41af1d490b to your computer and use it in GitHub Desktop.
Save hexadeciman/6fc0172f3d41af1d490b to your computer and use it in GitHub Desktop.
'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