n as
n as

Reputation: 619

How do I elegantly evaluate a continuous range in javascript?

I generate a random number between 0 and 1. I am probably using the wrong terminology, but I want an elegant way of evaluating the range.

Is there something 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

Upvotes: 4

Views: 119

Answers (2)

adeneo
adeneo

Reputation: 318302

Something like

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

Upvotes: 5

Vengarioth
Vengarioth

Reputation: 684

The only thing i can think of would be:

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

But it really only changes the looks, javascript has no in-depth function set for floating point operations.

Upvotes: -1

Related Questions