Skip to content

Instantly share code, notes, and snippets.

@dashmug dashmug/inventory.js
Created Apr 16, 2017

Embed
What would you like to do?
class InventoryObject {
/**
* @param {string} name
* @param {number} price
*/
constructor(name, price) {
this.name = name;
this.price = price;
}
/**
* Return a discounted price without altering the object.
* @param {number} percent
* @returns {number}
*/
getDiscountedPrice(percent) {
// We work with cents in order to avoid float division
const priceInCents = this.price * 100
return Math.round(priceInCents * (100 - percent)/100) / 100
}
}
const Inventory = {
'000001': new InventoryObject('Banana Slicer', 2.99),
'000002': new InventoryObject('Three Wolves Tea Cozy', 14.95)
}
// Retrieve the price
console.log(Inventory['000001'].price) // 2.69
// Retrieve a discounted price (e.g. ten percent off)
console.log(Inventory['000001'].getDiscountedPrice(10)) // 2.69
// Create a new inventory object from a discounted price
Inventory['000003'] = new InventoryObject('Bargain Banana Slicer', Inventory['000001'].getDiscountedPrice(10))
console.log(Inventory['000003']) // InventoryObject { name: 'Bargain Banana Slicer', price: 2.69 }
// Reduce the price of Banana Slicer by 10%
Inventory['000001'].price = Inventory['000001'].getDiscountedPrice(10)
console.log(Inventory['000001']) // InventoryObject { name: 'Banana Slicer', price: 2.69 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.