function getSizes(baseSize, sVariance) {
var sizes = [];
for (i = 0; i < 5; i++) {
sizes[i] = Math.ceil(baseSize - (Math.random() * sVariance));
}
return sizes;
}
function calculateOpacityValues(baseSize, sVariance) {
var min = 0.25, max = 1,
step = 0.75 / sVariance, i,
opacityValues = {};
for (i = 0; i <= sVariance; i++) {
opacityValues[baseSize - i] = min + step * i;
}
return opacityValues;
}
function getOpacities(sizes, opacityValues) {
// create a map of opacities
// and your expected values
var opacities = [];
sizes.forEach(function(value, index) {
opacities[index] = opacityValues[value];
});
return opacities;
}
var baseSize = 60, sVariance = 3,
sizes = getSizes(baseSize, sVariance);
console.log(sizes);
// use the map to get the opacity
console.log(getOpacities(sizes, calculateOpacityValues(baseSize, sVariance)));
You can see it in action here. It uses the forEach construct which is not supported in older browsers, but if you need to, you'll be able to switch it to a normal for loop. I've also refactored your code a bit by moving all the generation logic in the getSizes
method and all the opacity calculation in the getOpacities
method.
On a sidenote, you should use console.log
for debugging (this logs in FireBug's console on FireFox, in the Chrome WebInspector window or in the IE development console). This is a lot better than document.write
(this is true for this case also, even if we're not talking about alert
here).
Edit
You didn't mention if you want the baseSize
and the variance
to be variable. In that case, you should add a method to generate the opacity value map based on your logic.
I've added the logic you requested in the sample and I've updated the code.