Add cart pricing module
This commit is contained in:
+25
@@ -0,0 +1,25 @@
|
||||
export interface CartItem {
|
||||
sku: string
|
||||
name: string
|
||||
unitPriceCents: number
|
||||
quantity: number
|
||||
}
|
||||
|
||||
export interface Discount {
|
||||
code: string
|
||||
percentOff: number
|
||||
}
|
||||
|
||||
export function subtotalCents(items: CartItem[]): number {
|
||||
return items.reduce((sum, item) => sum + item.unitPriceCents * item.quantity, 0)
|
||||
}
|
||||
|
||||
export function applyDiscount(subtotal: number, discount?: Discount): number {
|
||||
if (!discount) return subtotal
|
||||
const factor = 1 - discount.percentOff / 100
|
||||
return Math.round(subtotal * factor)
|
||||
}
|
||||
|
||||
export function totalCents(items: CartItem[], discount?: Discount): number {
|
||||
return applyDiscount(subtotalCents(items), discount)
|
||||
}
|
||||
Reference in New Issue
Block a user