Skip to content

Instantly share code, notes, and snippets.

@florestankorp
Created September 29, 2018 09:26
Show Gist options
  • Save florestankorp/3406d56979659e5af198b73d097c0089 to your computer and use it in GitHub Desktop.
Save florestankorp/3406d56979659e5af198b73d097c0089 to your computer and use it in GitHub Desktop.
/*
You Don't Know JS: Up & Going
Chapter 1: Into Programming - PRACTICE
https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch1.md
*/
let accountBalance = 303.91;
let totalPriceOfPurchase = 0;
const TAX_RATE = 0.08;
const PHONE_PRICE = priceWithTax(99.99);
const ACCESSORY_PRICE = priceWithTax(9.99);
const SPENDING_THRESHOLD = 50;
export function buy(): string {
let phoneCounter = 0;
let accessoryCounter = 0;
while (totalPriceOfPurchase < accountBalance) {
accountBalance -= PHONE_PRICE;
totalPriceOfPurchase += PHONE_PRICE;
phoneCounter++;
if (accountBalance > SPENDING_THRESHOLD) {
accountBalance -= ACCESSORY_PRICE;
totalPriceOfPurchase += ACCESSORY_PRICE;
accessoryCounter++;
}
}
return formatPrice(
totalPriceOfPurchase,
phoneCounter,
accessoryCounter,
);
}
function priceWithTax(price: number): number {
return price + (price * TAX_RATE);
}
function formatPrice(
price: number,
phoneCount: number,
accessoryCount: number,
): string {
return `You've spent $ ${price.toFixed(2)} on ${phoneCount} phones and ${accessoryCount} accessories`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment