Skip to content

Instantly share code, notes, and snippets.

@fireonmac
Last active March 4, 2023 06:58
Show Gist options
  • Save fireonmac/aaeec35d3f207f72a52787487d96c3fc to your computer and use it in GitHub Desktop.
Save fireonmac/aaeec35d3f207f72a52787487d96c3fc to your computer and use it in GitHub Desktop.
functional_1
type Product = {
name: string;
price: number;
}
type ShoppingCart = Product[];
const TAX_RATE = 0.1;
const FREE_SHIPPING_PRICE_THRESHOLD = 20;
const MINIMUM_SHIPPING_COST = 5;
let shopping_cart: ShoppingCart = [];
function add_item_to_cart(cart: ShoppingCart, item: Product) {
return [...cart, item];
}
function calc_cart_total(cart: ShoppingCart) {
return cart.reduce((total, product) => total + product.price, 0);
}
function calc_tax_total(cart: ShoppingCart, tax_rate: number) {
return calc_cart_total(cart) * tax_rate;
}
function is_free_shipping(cart: ShoppingCart, price_threshold: number) {
return calc_cart_total(cart) > price_threshold;
}
function calc_shipping_cost(cart: ShoppingCart, minimum_shipping_cost: number) {
return cart.reduce(
(total, product) => total, // + shipping cost calculation by each product
minimum_shipping_cost
);
}
function calc_order_total(cart: ShoppingCart, tax_rate: number) {
const shipping_cost = is_free_shipping(cart, FREE_SHIPPING_PRICE_THRESHOLD)
? 0
: calc_shipping_cost(cart, MINIMUM_SHIPPING_COST)
return calc_cart_total(cart)
+ calc_tax_total(cart, tax_rate) + shipping_cost;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment