Untitled
unknown
plain_text
a year ago
1.2 kB
10
Indexable
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 };
Editor is loading...
Leave a Comment