Files
v2.app.gaertan.art/src/utils/calculatePrice.ts
2026-01-31 16:04:29 +01:00

48 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

type PriceSource = {
price?: number | null
pricePercent?: number | null
priceRange?: string | null
}
export function calculatePrice(source: PriceSource, base: number): number {
if (source.price != null) return source.price
if (source.pricePercent != null) return base * (source.pricePercent / 100)
if (source.priceRange) {
const parts = source.priceRange.split("").map(Number)
const max = Math.max(...parts)
return Number.isNaN(max) ? 0 : max
}
return 0
}
export function calculatePriceRange(
baseSource: PriceSource | undefined,
extras: PriceSource[]
): [number, number] {
if (!baseSource) return [0, 0]
const base = calculatePrice(baseSource, 0)
let minExtra = 0
let maxExtra = 0
for (const extra of extras) {
if (extra.price != null) {
minExtra += extra.price
maxExtra += extra.price
} else if (extra.pricePercent != null) {
const val = base * (extra.pricePercent / 100)
minExtra += val
maxExtra += val
} else if (extra.priceRange) {
const [minStr, maxStr] = extra.priceRange.split("")
const min = Number(minStr)
const max = Number(maxStr)
if (!Number.isNaN(min)) minExtra += min
if (!Number.isNaN(max)) maxExtra += max
}
}
return [base + minExtra, base + maxExtra]
}