I'm attempting to create a function that will give me a "fish" at random, though a bias random depending on the weight value for the "fish".
var FISH = {
"level1": [
//["name", xp, weight]
["Shrimp", 10, 95],
["Sardine", 20, 85],
["Herring", 30, 75],
["Anchovies", 40, 65],
["Mackerel", 40, 55]
]
};
function randomRange(min, max) {
return Math.random() * (max - min) + min;
}
function getRandomFish(level) {
var fishForLevel = FISH[level],
numberOfFish = fishForLevel.length,
chance = randomRange(0, 100);
if (numberOfFish > 1) {
var fish = fishForLevel[Math.floor(randomRange(0, numberOfFish))];
if (chance <= fish[2]) {
return fish;
} else {
return getRandomFish(level);
}
} else {
return fishForLevel[0];
}
}
Example of outcome: http://jsfiddle.net/qAvAs/
If this could be made more efficient, how would one do so?