Yamika Izumi
Yamika Izumi

Reputation: 19

Dynamic Switch in Javascript

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?

Upvotes: 1

Views: 3828

Answers (2)

baao
baao

Reputation: 73251

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)

Upvotes: 1

Muhammad Usman
Muhammad Usman

Reputation: 10148

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

Upvotes: 0

Related Questions