An easy way to test many different cases

So I was wondering if it could be made easier if the statements with math.random without using switch () like this:

var ex = Math.random()

if (ex > 0.1) {
    return 'so long';
} else if (ex > 0.2) {
    return 'so long'; // i understand that this is dead code because it does the same thing, its just for example
}

      

etc.

it repeats quickly and i think there must be an easier way to do this

+3


source to share


2 answers


If you want to select a random entry from a set of rows, you can do it like this:

var options = ["So long", "Thanks for all the fish", "42", "Where is my towel?"];
var index = Math.floor(Math.random() * options.length);
return options[index];

      



PS: Couldn't Ford at some point have assumed that Arthur could be replaced by a robot that asks for a cup of tea? Unfortunately I cannot find the original quote ...

+2


source


Just use a for loop:

var ex = Math.random();

var returnPhrases = [
    'so long',              // this will be returned if (ex > 0.1)
    'so long',              // this will be return if (ex > 0.2)
    'thx for all the fish', // this will be returned if (ex > 0.3)
    'so long',              // etc.
    '42',
    'thanks for all the fish',
    'so long',
    'thx for all the fish',
    'so long',
    '42'
]

for (var i=0;i<1;i+=0.1) {
    if (ex > i) {
        return returnPhrases[i*10];
    }
}

      



This will work for your specific case and many similar recurring cases.

0


source







All Articles