class Buyer { constructor(market) { this.market = market; } /** * Build an order preference table for particular product * @param product */ buildOrderPreference(product) { let sellers = []; // build up the initial list this.market.sellers.forEach((seller, i) => { if (seller.inventory.hasOwnProperty(product)) { const price = seller.quote(product); sellers.push({id: seller.id, price: price, index: i, quantity:seller.inventory[product].quantity}) } }); // sort by best price sellers.sort((a, b) => { return a.price - b.price; }) return sellers; } /** * This method should get the best price for a given product * across all sellers */ getBestPrice(product) { let lowestPrice = null; this.market.sellers.forEach(seller => { if (seller.inventory.hasOwnProperty(product)) { const price = seller.quote(product); if (lowestPrice === null || lowestPrice > price) lowestPrice = price; } }); return lowestPrice || 0; } /** * This method should optimise price when filling an order * if the quantity is greater than any single seller can accomodate * then the next cheapest seller should be used. */ fillWithBestPrices(product, quantity) { let wantedQuantity = quantity; let sellerPreference = this.buildOrderPreference(product); console.log(sellerPreference); let reciept = []; while (sellerPreference.length > 0 && wantedQuantity > 0) { let seller = sellerPreference.shift(); let r = this.market.sellers[seller.index].sell(product, wantedQuantity); wantedQuantity = (wantedQuantity - r.boughtQuantity) < 0 ? 0 : (wantedQuantity - r.boughtQuantity); reciept.push(r); } console.log(reciept); console.log(reciept.reduce((a, cv) => { return a.cost + cv.cost; }) ); throw Error("Not Implemented"); } /** * This method should optimise for sellers with the largest inventory when filling an order * if the quantity is greater than any single seller can accomodate * then the next largest seller should be used. * if multiple sellers have the same amount of inventory * you should use the cheaper of the two. */ fillWithLargestSellers(product, quantity) { throw Error("Not Implemented"); } } module.exports = {Buyer}