1

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?

1
  • The switch would 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 Commented Jun 3, 2018 at 13:50

2 Answers 2

1

Use an object literal - that makes it much easier and faster as you don't have to loop the array everytime you lookup something. It's also easier to handle dynamically than a switch

const foo = {
  Plains: Plains,
  Mountains: ImpassableMountains
}

let x = 'Plains';

foo[x].create(newPosition)
Sign up to request clarification or add additional context in comments.

Comments

0

You can simply use .indexOf to check if it's in that array and perform actions accordingly.

terrainArray.indexOf(terrain) >=0 ? Terrain.create(newPosition) : null;

To

it will go through the entire array., To find something in array it will.. always

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.