Untitled
unknown
plain_text
a year ago
979 B
20
Indexable
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 };
Editor is loading...
Leave a Comment