Untitled
unknown
plain_text
17 days ago
979 B
3
Indexable
Never
interface ISaleOffer { price: number; amount: number; } function calculateOrder(amount: number, salesBook?: ISaleOffer[] | null): any { if (amount < 0 || !Array.isArray(salesBook)) { return { amount: 0, price: 0, }; } const salesBookSorted = [...salesBook].sort((a, b) => a.price - b.price); const totalAmount = salesBookSorted.reduce((prev, curr) => (prev += curr.amount), 0); const amountSold = totalAmount >= amount ? amount : totalAmount; let remaining = amountSold; let price = 0; for (let i = 0; i < salesBookSorted.length; i++) { const currentOffer = salesBookSorted[i]; if (remaining - currentOffer.amount > 0) { remaining -= currentOffer.amount; price += currentOffer.price * currentOffer.amount; } else { price += currentOffer.price * remaining; break; } } return { amount: amountSold, price: Math.round(price * 100) / 100, }; } export { calculateOrder, ISaleOffer };
Leave a Comment