// Pass the item list and the desired category as arguments:
var findItem = function(items, category, desiredItem) {
// apply filter to items, so only those of the given category remain:
items = items.filter( item => item.category == category );
// rest of code remains the same:
var possible = items.some( ({item, probability}) =>
item === desiredItem && probability > 0 );
if (!possible) {
console.log('There is no chance you\'ll ever find a ' + desiredItem);
return;
}
var sum = items.reduce( (sum, {item, probability}) => sum+probability, 0 );
var t = 10;
while (true) {
var value = Math.random() * sum;
var lootedItem = items.find(
({item, probability}) => (value -= probability) <= 0 ).item;
if (lootedItem === desiredItem) break; // fixed this condition!
console.log("Dang! A " + lootedItem + " was found...");
t--; if (t <= 0) throw "loop";
}
console.log("Lucky! A " + desiredItem + " was found!");
}
// Define items here with their category
var items = [
{ item: "rusty nail", probability: 0.25, category: 2 },
{ item: "stone", probability: 0.23, category: 2 },
{ item: "banana", probability: 0.20, category: 2 },
{ item: "leaf", probability: 0.17, category: 5 },
{ item: "mushroom", probability: 0.10, category: 5 },
{ item: "diamond", probability: 0.05, category: 10 }
];
// Call function with extra arguments:
findItem(items, 5, 'mushroom');
console.log('second run:');
// This will obviously give a hit immediately, as there is only one possible item:
findItem(items, 10, 'diamond');