How can I elegantly evaluate continuous range in javascript?

I generate a random number between 0 and 1. I probably use the wrong terminology, but I need an elegant way to evaluate the range.

Is there anything better than the following?

if (RandNum < 0.075) { sVal = 'a'; }
else if (RandNum < 0.123) { sVal = 'b'; }
else if (RandNum < 0.199) { sVal = 'c'; }
... etc
+4
source share
2 answers

Sort of

var RandNum = Math.random(),
    letter  = null,
    obj = {
        a : 0.075,
        b : 0.123,
        c : 0.199,
        d : 0.2,
        e : 0.4,
        f : 0.6,
        g : 0.8,
        h : 1
}

for (var k in obj) {
    if (RandNum < obj[k]) {
        letter = k;
        break;
    }
}

Fiddle

or with two arrays instead

var RandNum = Math.random(),
    letters  = 'abcdefgh'.split(''),
    range = [
        0.075,
        0.123,
        0.199,
        0.2,
        0.4,
        0.6,
        0.8,
        1
    ];

while (RandNum < range.pop());
var letter = letters[range.length];

Fiddle

+5
source

The only thing I can think of:

switch(true) {
    case (RandNum < 0.075):
        sVal = 'a';
        break;
    case (RandNum < 0.123):
        sVal = 'b';
        break;
    ...
}

But this really only changes the look and feel, javascript has no built-in function for floating point operations.

-1
source

All Articles