Untitled
unknown
plain_text
17 days ago
1.2 kB
2
Indexable
Never
interface ISaleOffer { price: number; amount: number; } function calculateOrder(amount: number, salesBook?: ISaleOffer[] | null): any { const isSalesBookArray = Array.isArray(salesBook); if (amount < 0 || !isSalesBookArray) { return { amount: 0, price: 0, }; } const salesBookCloned = [...salesBook]; const salesBookSorted = salesBookCloned.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 items: ISaleOffer[] = []; for (let i = 0; i < salesBookSorted.length; i++) { const currentOffer = salesBookSorted[i]; if (remaining - currentOffer.amount > 0) { remaining -= currentOffer.amount; items.push(currentOffer); } else { currentOffer.amount = remaining; items.push(currentOffer); break; } } const price = items.reduce((prev, curr) => prev + curr.amount * curr.price, 0); return { amount: amountSold, price: Math.round(price * 100) / 100, }; } export { calculateOrder, ISaleOffer };
Leave a Comment