Reputation: 317
I have a main function and want to control 2 actions with it. Thereby I pass different variables to the function.
My question is whether I can also pack the condition of an If query into a variable.
For the one action I want to have CurrentImageNumber <= 3
as an if argument and for the other action CurrentImageNumber >= 2
in the if query.
The code would look something like this:
function imageChange() {
CurrentImageNumber = parseInt(CurrentImageID.slice(-1)) // not a static value
if (b) {
// Some fancy Code where var a is used
}
else {
// Some fancy Code where var c is used
}
}
document.getElementById('button-1').onclick = function() {
imageChange(a = 1, b = CurrentImageNumber <= 3, c = -3)
}
document.getElementById('button-2').onclick = function() {
imageChange(a = -1, b = CurrentImageNumber >= 2, c = 2)
}
Upvotes: 1
Views: 3890
Reputation: 81
Yes you could do this, but what actually happens is, the condition is checked and the predicate
returns a boolean
value which is parsed into the function.
This would be done like so:
doStuff(CurrentImageNumber <= 4);
function doStuff(a) {
if (a) {
// Execute some fancy code
}
}
But what actually happens during runtime is equivalent to this: Lets say CurrentImageNumber == 0:
const predicateResult = CurrentImageNumber <= 4;
// Here predicateResult is of type boolean and is true
doStuff(predicateResult);
function doStuff(a) {
if (a) {
// Execute some fancy code
}
}
Upvotes: 2
Reputation: 782693
The function needs a parameter variable to get the argument.
doStuff(CurrentImageNumber >= 2)
doStuff(CurrentImageNumber <= 4)
function doStuff(a) {
if (a) {
// execute some fancy code
}
}
Upvotes: 0