I'm trying to optimize my code to be more efficient and easier to read. I have some combined if-statements, which I think could be better, if they are transformed to for-loops, I'm just not sure how to do this?
This is my code:
if (starportSelected){
if(game.currentLevel.requirements.vehicles.indexOf('transport')>-1 && cashBalance>=vehicles.list["transport"].cost){
$("#transportbutton").removeAttr("disabled");
}
if(game.currentLevel.requirements.vehicles.indexOf('scout-tank')>-1 && cashBalance>=vehicles.list["scout-tank"].cost){
$("#scouttankbutton").removeAttr("disabled");
}
if(game.currentLevel.requirements.vehicles.indexOf('heavy-tank')>-1 &&cashBalance>=vehicles.list["heavy-tank"].cost){
$("#heavytankbutton").removeAttr("disabled");
}
if(game.currentLevel.requirements.vehicles.indexOf('harvester')>-1 && cashBalance>=vehicles.list["harvester"].cost){
$("#harvesterbutton").removeAttr("disabled");
}
if(game.currentLevel.requirements.aircraft.indexOf('chopper')>-1 && cashBalance>=aircraft.list["chopper"].cost){
$("#chopperbutton").removeAttr("disabled");
}
if(game.currentLevel.requirements.aircraft.indexOf('wraith')>-1 && cashBalance>=aircraft.list["wraith"].cost){
$("#wraithbutton").removeAttr("disabled");
}
}
I think first step would be to create two arrays, one for vehicles and one for aircrafts like this:
var vehicles = ['transport', 'scout.tank', 'heavy-tank', 'harvester'];
var aircraft = ['chopper', 'wraith'];
But how to take the rest of the code and change it to for-loop seems like a hard case for me. All help and explanation would be highly appreciated!
var foo = game.currentLevel.requirements.vehicles;and thenfoo.indexOf('blah')game.currentLevel.requirements.aircraft.indexOfandgame.currentLevel.requirements.vehicles.indexOfare to different lines.