84 lines
1.9 KiB
JavaScript
84 lines
1.9 KiB
JavaScript
|
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 => {
|
||
|
if (seller.inventory.hasOwnProperty(product)) {
|
||
|
const price = seller.quote(product);
|
||
|
sellers.push({id:seller.id, price:price})
|
||
|
}
|
||
|
|
||
|
});
|
||
|
|
||
|
// 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 sellerPreference = this.buildOrderPreference(product);
|
||
|
|
||
|
console.log(sellerPreference);
|
||
|
|
||
|
while(sellerPreference.length > 0) {
|
||
|
|
||
|
let seller = sellerPreference.shift();
|
||
|
|
||
|
|
||
|
|
||
|
}
|
||
|
|
||
|
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}
|