Skip to content

Instantly share code, notes, and snippets.

@kennyxcao
Created September 21, 2017 16:59
Show Gist options
  • Save kennyxcao/ee45c50e6fa55276de1af9f2f0715721 to your computer and use it in GitHub Desktop.
Save kennyxcao/ee45c50e6fa55276de1af9f2f0715721 to your computer and use it in GitHub Desktop.
// Prompt: tackling floating-point imprecision with the CashAmount class
class CashAmount {
constructor(double) {
this.pennies = parseInt(double * 100, 10);
}
totalInPennies() {
return this.pennies;
}
toDouble() {
return this.pennies / 100;
}
toDoubleString() {
return this.toDouble().toString();
}
addDoubleAmount(double) {
this.pennies += parseInt(double * 100, 10);
}
quantityOfEachDenomination() {
const denominations = ['hundreds', 'fifties', 'twenties', 'tens', 'fives', 'ones', 'quarters', 'dimes', 'nickels', 'pennies'];
const values = [10000, 5000, 2000, 1000, 500, 100, 25, 10, 5, 1];
let results = {};
let remaining = this.pennies;
for (let i = 0; i < values.length; i++) {
if (values[i] > remaining) {
results[denominations[i]] = 0;
} else {
results[denominations[i]] = Math.floor(remaining / values[i]);
remaining -= values[i] * results[denominations[i]];
}
}
return results;
}
}
class TestSuite {
runTests() {
this.testTotalInPennies();
this.testAddDoubleAmount();
this.testToDouble();
this.testToDoubleString();
this.testFloatArithmetic();
this.testQuantityOfEachDenomination();
}
testTotalInPennies() {
const cash = new CashAmount(10.50);
console.log(cash.totalInPennies() + ' should equal 1050');
}
testAddDoubleAmount() {
const cash = new CashAmount(10.50);
cash.addDoubleAmount(29.33);
console.log(cash.totalInPennies() + ' should equal 3983');
}
testToDouble() {
const cash = new CashAmount(10.50);
console.log(cash.toDouble() + ' should equal 10.50');
}
testToDoubleString() {
const cash = new CashAmount(10.50);
console.log(cash.toDoubleString() + ' should equal "10.50"');
}
testFloatArithmetic() {
const cash = new CashAmount(0.10);
cash.addDoubleAmount(0.20);
console.log(cash.toDouble() + ' shoulde equal 0.30');
}
testQuantityOfEachDenomination() {
const cash = new CashAmount(967.93);
const expected = '{hundreds: 9, fifties: 1, twenties: 0, tens: 1, fives: 1, ones: 2, quarters: 3, dimes: 1, nickels: 1, pennies: 3 }';
console.log(cash.quantityOfEachDenomination());
console.log(' should equal ' + expected);
}
}
const suite = new TestSuite();
suite.runTests();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment