Last active
August 29, 2015 14:12
-
-
Save maxant/8996ce430ba22246a84e to your computer and use it in GitHub Desktop.
The trading function of the market.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
this.trade = function(){ | |
var self = this; | |
var sales = []; | |
var productsInMarket = this.getProductsInMarket().values(); | |
... | |
//trade each product in succession | |
_.each(productsInMarket, function(productId){ | |
var soldOutOfProduct = false; | |
logger.debug('trading product ' + productId); | |
var buyersInterestedInProduct = self.getBuyersInterestedInProduct(productId); | |
if(buyersInterestedInProduct.length === 0){ | |
logger.info('no buyers interested in product ' + productId); | |
}else{ | |
_.each(buyersInterestedInProduct, function(buyer){ | |
if(!soldOutOfProduct){ | |
logger.debug(' buyer ' + buyer.name + ' is searching for product ' + productId); | |
//select the cheapest seller | |
var cheapestSeller = _.chain(self.sellers) | |
.filter(function(seller){return seller.hasProduct(productId);}) | |
.sortBy(function(seller){return seller.getCheapestSalesOrder(productId).price;}) | |
.first() | |
.value(); | |
if(cheapestSeller){ | |
logger.debug(' cheapest seller is ' + cheapestSeller.name); | |
var newSales = self.createSale(buyer, cheapestSeller, productId); | |
sales = sales.concat(newSales); | |
logger.debug(' sales completed'); | |
}else{ | |
logger.warn(' market sold out of product ' + productId); | |
soldOutOfProduct = true; | |
} | |
} | |
}); | |
} | |
}); | |
return sales; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment