I want to do a switch with dynamic content in javascript, I will put an example:
switch(terrain) {
case "Plains":
terrain = Plains.create(newPosition);
break;
case "Mountains":
terrain = ImpassableMountain.create(newPosition);
break;
case "Hills":
terrain = Hills.create(newPosition);
break;
case "Forest":
terrain = Forest.create(newPosition);
break;
case "River":
terrain = River.create(newPosition);
break;
default:
};
So if I want to add a new Terrain for example Ocean, I want that will be updated automatically. I am thinking about to put all the terrains in a array
var terrainArray = ["Plains","Mountains","Hills","Forest","River","Ocean",...]
But I don't know how to put that in a switch in the most optimized way because if I try
for(var i=0;i<terrainArray.length;i++){
if(terrain==terrainArray[i]){
Terrain.create(newPosition);
}
}
It wouldn't be optimized because it will go through the entire array.
Also I need to put the class dynamically so if that terrain is Plains I need to put Plains.create instead of other, maybe can I do that with an array of classes?
switchwould usually go through all cases as well. I don't think this code is in a bottleneck position anyway where it would matter for performance