Suppose I have a snippet like this,
let arr = [{...},{...} ...]// huge array of objects;
arr.forEach(i => {
if(someOtherProperty == "one") {
...
} else if(someOtherProperty == "two") {
...
}...
})
Basically, I have an if-else-if ladder inside a loop.
The condition does not depend on the array item.
I want to know if it is possible to evaluate the if condition prior to execution of the loop since the condition is static/constant throughout the loop run
Few ways I can think of is
- keep the loop inside each of the if/else blocks. This way the if condition will be executed only once but I have more codes.
-
Use an object like
let condition = { one: someOtherProperty == "one", two: someOtherProperty == "two", ... }
And use it in the condition like if(condition.one) and so on.
Please suggest a better way to deal with situations like this to improve the efficiency.
Aucun commentaire:
Enregistrer un commentaire