1
I wanted to think of a logic that would decrease the size of this code, because it ends up repeating itself.
It is an experience calculator for a game. You set your current level and the level you want to reach. The game has normal level ranging from 1 to 399 and the master level from 400 to 1300.
Basically I need to check that both the current level and the desired level are in the correct category (whether it is in normal or master).
Notice that both the if
of currentLevel
as to the desiredLevel
are practically identical, only changes even if one is for the current
and the other is for the desired
.
Pay no attention to array have more variables, I only brought the part that interests me here. The function has more than that.
let checkfields = [currentLevel, desiredLevel, currentExp, expSec, hoursDay]
function checkFieldInsert(normalInitialLevel, masterInitialLevel){
for (let i = 0; i <= checkfields.length; i++){
if (checkfields[i] == currentLevel){
if (levelMaster.checked && parseInt(checkfields[i].value) < 400){
alert(`this ${checkfields[i].value} is not master level`)
break
}
else if (levelNormal.checked && parseInt(checkfields[i].value) >= 400){
alert(`this ${checkfields[i].value} is not normal level`)
break
}
} else if (checkfields[i] == desiredLevel){
if (levelMaster.checked && parseInt(checkfields[i].value) < 400){
alert(`this ${checkfields[i].value} is not master level`)
break
}
else if (levelNormal.checked && parseInt(checkfields[i].value) >= 400){
alert(`this ${checkfields[i].value} is not normal level`)
break
}
}
}
}
Wow, it worked! I didn’t know I could use parentheses like that... I had tried to do exactly the same thing you did, but without the parentheses and it didn’t work out. Thank you very much.
– Christian