what i have now is a function that return an array of 2 string that were put together using a random number generator. those values will help make up a string like "this is" + v1 + " and this is" + v2. v1 and v2 are the dynamically created strings. I need to do operations depending on the values of the string. my problem is that im not sure on how to do an efficient comparison of all the different ways the v1 and v2 represent. I think I would have to do a lot of if statements like the way i will show in the code. I know there is a better way to do the comparisons. What is it?
//the unit function makes sure that a random letter is returned but also makes sure that
the first letter returned comes before the second letter in the values array
function unit(){
var values = ["a", "b", "c", "d", "e" , "f"];
var value1 = Math.floor(Math.random() * (values.length - 1)) + 1;
var value2 = Math.floor(Math.random() * value1);
if(value1 !== value2){
return [values[value2], values[value1]];
}
}
//pseusodo-code
// i have to do a different operation dependeng on the values of v1 and v2
//bad code
function conversion(v1, v2, num){
if(v1 == "a" && v2 == "b"){
return 16 * num
}
if(v1 == "a" && v2 == "c"){
return 32 * num
}
if(v1 == "a" && v2 == "d"){
return 64 * num
}
if(v1 == "a" && v2 == "e"){
return 256 * num
}
if(v1 == "b" && v2 == "c"){
return 18 * num
}
if(v1 == "b" && v2 == "d"){
return 20 * num
}
if(v1 == "b" && v2 == "e"){
return 64 * num
}
if(v1 == "b" && v2 == "f"){
return 256 * num
}
etc
}
function string(){
u = unit()
v1 = u[0];
v2 = u[1]
return "this is " + v1 + " and this " + v2
}
console.log(string())
// for every 2 a theres 1 b's
//for every 16 a there 1 c
//for every 32 a there is 1 d
//for every 64 a there is 1 e
conversion(v1,v2, 2.5)
console.log(v1, " ", v2)
Can't you create a lookup object which holds all the multiplication factors? Think of this as if it were a two-dimensional table:
Then the conversion function becomes:
Note that while I hand-coded the values in the
factors
object above, its values can also be set programatically.