I am making an javascript game, featuring several levels, stored in json. When loading, I run a function to "parse" the level object by replacing values that are not present by their default values, or by replacing some values by objects, such as:
//i is the variable I use to loop through the enemies
if (typeof(level.enemies[i].life)=="undefined") {
level.enemies[i].life=100;
}
if (typeof(level.enemies[i].follow)=="number") {
level.enemies[i].follow=level.enemies[level.enemies[i].follow];
// replace the number of the enemy,
// by a reference to the actual enemy.
}
The problem is that I have a lot of "ifs" similar to these throughout the function, and I am wondering if I somehow can reduce them to a function so I can do this:
replaceByType(level.enemies[i].life,"undefined",100);
replaceByType(level.enemies[i].follow,"number",level.enemies[level.enemies[i].follow]);
Sadly I don't know how to do this, because their is no way to pass a variable(other than an object) by reference. Maybe there is another way to simplify my code?