Skip to content

Instantly share code, notes, and snippets.

@pavangadagi
Last active January 11, 2024 12:04
Show Gist options
  • Save pavangadagi/278dfa88c2a6fdf51f2f7502c4ea0c13 to your computer and use it in GitHub Desktop.
Save pavangadagi/278dfa88c2a6fdf51f2f7502c4ea0c13 to your computer and use it in GitHub Desktop.
const DISCOUNT_TYPES = {
BUY_2_GET_3: "BUY_2_GET_3",
BULK: "BULK",
}
const ITEM_LIST = {
APPLE_TV: "atv",
SUPER_IPAD: "ipd"
}
type item = {
name: string,
price: number,
sku: string
}
// we can create multiple objects of PriceRules containing different kinds of discounts
class PriceRules {
prices: Map<string,number>;
constructor(priceList: Map<string,number>){
this.prices = priceList
}
// function will get the price of items with discounts applied if applicable
public getTotalPrice(item: string, quantity: number): number{
let price = 0;
// discount for item tv
if(item === ITEM_LIST.APPLE_TV && quantity === 3){
price = this.prices.get(item) * 2;
}
// discount for ipad
else if(item === ITEM_LIST.SUPER_IPAD && quantity === 4 ){
// 9.09% less
let newPrice = this.prices.get(item) - (this.prices.get(item)/100)*9.09;
price = newPrice * quantity;
}
// return other prices
else{
price = this.prices.get(item) * quantity;
}
return price;
}
}
class Checkout {
private cart:Map<string,number>;
private priceRules: PriceRules
constructor(priceRules: PriceRules){
this.priceRules = priceRules;
}
public scan(item: string): void{
this.cart.has(item) ? this.cart.set(item, this.cart.get(item)+1) : this.cart.set(item,1);
}
public total(): number{
let total = 0;
for(let key of this.cart.keys()){
// get price of each item
let itemPrice = this.priceRules.getTotalPrice(key,this.cart.get(key));
total += itemPrice;
}
return total;
}
}
// MAIN
// get the itemlist
// { ipd: 549.99, atv: 109.50 }
let itemPrices = new Map<string,number>([ [ "ipd", 549.99 ], [ "atv", 109.50 ]])
// create different pricerules
let priceRule = new PriceRules(itemPrices);
const co = new Checkout(priceRule);
co.scan();
co.scan(item2);
const total = co.total();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment