The best solution that comes to mind is using a functional approach for that.
let arr = [1,2,3,4,5,6,7,8,9]; // Huge array
let condFactory = (condition) => {
if (condition === 'one') {
console.log('This will only be called once, if condition==="one"',
'it will not be called for each element')
return (item, index) => console.log('one (called for each element)', item, index);
} else if (condition === 'two') {
console.log('This will only be called once, if condition==="two"',
'it will not be called for each element')
return (item, index) => console.log('two (called for each element)', item, index);
}
console.log('This will only be called once, if no condition matches',
'it will not be called for each element')
return (item, index) => console.log('No condition matched (called for each element)', item, index);
}
arr.forEach(condFactory(someOtherProperty));
For es5:
var arr = [1,2,3,4,5,6,7,8,9]; // Huge array
var condFactory = function(condition) {
if (condition === 'one') {
console.log('This will only be called once, if condition==="one"',
'it will not be called for each element')
return function(item, index) { console.log('one (called for each element)', item, index); };
} else if (condition === 'two') {
console.log('This will only be called once, if condition==="two"',
'it will not be called for each element')
return function(item, index) { console.log('two (called for each element)', item, index); };
}
console.log('This will only be called once, if no condition matches',
'it will not be called for each element')
return function(item, index) { console.log('No condition matched', item, index); };
}
arr.forEach(condFactory(someOtherProperty));
This way the function to be used for each condition will be determined before the loop starts and used for every element inside the loop.
You can stretch this oneliner
arr.forEach(condFactory(someOtherProperty));
into two lines to see why the if...else is only evaluated once:
let functionBasedOnIfElse = condFactory(someOtherProperty); // Get the function based on your "someOtherProperty"
arr.forEach(functionBaseOnIfElse); // Pass reference to the function
As you can see, the if...else will only be evaluated once. The returned function on that if...else will then be passed to arr.forEach and called for each element inside the array.
Edit: Added default return.
Edit2: Corrected es5 snipped
Edit3: Expands cases to show that each function is applied to each item inside the array.
Edit4: Adds more information on why the if...else is only evaluated once.
Edit5: Adds a few console.log
to show which part will be called at which point.