JEXL—the backbone of IMCScript—provides these important conditional syntax options.
If-else statements
If-else statements help to perform logic based on certain conditions. The following example uses if-else conditions to check whether a number is odd or even.
var number = 5;
var type;
if (number % 2 == 0)
{
type = 'EVEN';
}
else
{
type = 'ODD';
}
return type; // Outcome: 'ODD'
Alternatively, user can also have multiple else-if statements. Here is an example which sets fruit according to season.
var season = 'FALL';
var fruit;
if (season == 'WINTER')
{
fruit = 'KIWI';
}
else if (season == 'SPRING')
{
fruit = 'HONEYDEW';
}
else if (season == 'SUMMER')
{
fruit = 'DURIAN';
}
else if (season == 'FALL')
{
fruit = 'CRANBERRY';
}
else
{
fruit = 'APPLE';
}
return fruit; // Outcome: 'CRANBERRY'
For loop
For loops help to iterate List object types and perform specific logic for each of their elements. For example, the following code iterates through each element of list and sums values in variable sum.
var list = List.create(1,6,3,1,5,9,7,8,2,4);
var sum = 0;
for (var eachItem in list) // Loops each item of list
{
sum = sum + eachItem;
}
return sum; // Outcome: 46
While loop
While loops help iteratively perform required logic until a specific condition is not violated. The following example uses a while loop to iterate through numbers until it doesn't find the square root of a given number.
var number = 81;
var squareRoot;
var i = -1;
var found = false;
while (!found)
{
i = i + 1;
if (i * i == number)
{
squareRoot = i;
found = true;
}
else
{
found = false;
}
}
return squareRoot; // Outcome: 9
Alternatively, continue and break are useful reserved keywords which help to skip or break the loops unconditionally. Calculable usage of these keywords improves script execution time by skipping or breaking execution of insignificant loops.
The following script finds a number in a list and breaks the loop using break keyword once it finds the number inside the list.
var list = List.create(10,90,20,30,50,40,70);
var numberToFind = 30;
var found = false;
for (var eachItem : list)
{
if (eachItem == numberToFind)
{
found = true;
break; // Breaks loop once element is found
}
}
return found; // Outcome: true
Custom functions
Custom or user-defined functions enable you to reuse custom logic in the same script. It also increases readability for the script.
The following example defines two simple custom functions—sum and multiplication—for two numbers. The important thing to note is that you should define the function before using it.
var sum = function(a, b) // Definition of custom method 'sum'
{
return a + b;
};
var mul = function(a, b) // Definition of custom method 'mul'
{
return a * b;
};
var result1 = sum(5, 3); // Outcome: 9
var result2 = mul(3, 4); // Outcome: 12