How can a nested conditional like the one below be optimized for improved performance and readability? To enhance efficiency, it would be beneficial to consolidate repetitive entries into a more practical function due to loops within many potential cases.
//a is set to 1, 2, or 3
//b is either true or false
for(var i=0; i<hugeNumber; i++){
switch(a){
case 1:
if(b){
for(objects in longlist){
objects.color = object.c;
objects.position = object.x
}
}else{
for(objects in longlist){
objects.color = object.c;
objects.position = object.y
}
case 2:
if(b){
for(objects in longlist){
objects.color = object.b;
objects.position = object.x;
}
}else{
for(objects in longlist){
objects.color = object.b;
objects.position = object.y;
}
case 3:
if(b){
for(objects in longlist){
objects.color = blackColor;
objects.position = object.x;
}
}else{
for(objects in longlist){
objects.color = blackColor;
objects.position = object.y;
}
}
}
Adding conditionals within an overarching for loop seems equally unreasonable.
It would be ideal to define the target variable at the start when the conditions are known - where condition a always determines color c for 0, color b for 1, and blackColor for 2, while condition b always dictates position x for true and position y for false.
I have encountered similar questions regarding PHP and Ruby, but adapting solutions to JavaScript poses some challenges. While there are potential strategies, I have not yet been able to execute syntactically correct code.
UPDATE / SOLUTION: After receiving input, I found that this task can be efficiently accomplished using eval()
:
var targetColor;
var targetPosition;
switch(a){
case 1: targetColor = "objects.c"; break;
case 2: targetColor = "objects.b"; break;
case 3: targetColor = "blackColor"; break;
}
if(b){
targetPosition = "objects.x";
}else{
targetPosition = "objects.y";
}
for(var i=0; i<hugeNumber; i++){
for(objects in longlist){
objects.color = eval(targetColor);
objects.position = eval(targetPosition);
}
}
If there is a better alternative to this approach, I am open to additional suggestions as I am aware of the potential risks associated with using eval.