I want to be clear, this advanced functionality and will not be on the final Certification Exam. Also, remember, we are to help you create the rules that you need for your goals.
If you get stuck or want some help, open a chat, we have an entire rule library of crazy stuff that is already written, so we can find you a rule that will work for your business case.
Basics
OpsScript is a language designed for businesses with limited or no programming experience. It provides a simple yet powerful syntax for writing scripts to automate tasks and workflows. OpsScript shares many design characteristics common among popular languages, but is tailor made for the OpsAnalitica platform. OpsScript is a case-insensitive, strongly typed scripting language that executes on client devices and in the cloud.
Rules Vs Scripts
Pre-Create Response Rules or Rules run in checklists on the device.
Post-Create Response Scripts or Scripts run on the server after the checklist has been submitted.
Scripts aren't in use yet, they show in the UI as a placeholder for future development.
When you are writing a rule, you are technically writing a script that we use as a Rule. If you see the word script that is what we are referring to.
Script Logic Evaluation:
Scripts run from top to bottom. Meaning that the script starts evaluating logic on line 1 and continues to the bottom.
You have to account for all possibilities of the response.
When writing rules always take into account could there be nulls and make sure you account for them.
Ex: on a True-False question the Possibilities are:
True Response
False Response
N/A Response
Not answering the question, a Null Response, is the same of the an N/A.
Rule: Pass/Fail
A Rule is a script that returns a pass or a fail.
Pass means the rule logic is executed without any issues.
Fail: this will mark the question as a validation error.
You need to Return.This.Fail with a message of what to do.
All Rules must return a Pass or a Fail.
You can stop a script from running by returning a pass.
Return This.Pass()
You can stop a script from running and require the end user to take an action by returning a Fail.
Return This.Fail("Please enter a comment")
The "Please enter a comment" text is shown to the end user.
When you return an item a Fail you need to have the end user take an action that satisfies the fail logic so that it doesn't stop the rule from eventually passing.
Ex: You require a comment in the rule. The end user leaves a comment. That Failure is handled and the rule can continue.
Case Sensitivity
The scripting language is not case sensitive.
Text that is being looked for in a rule from the platform is.
If you are looking for a question with a tag named Follow-up, then the tag on the question has to be an exact match to the tag in the rule.
In the above example the tag on the question would not be recognized if it was spelled like this: follow-up.
Tags and Values are Case Sensitive.
Expressions
Expressions are the core of OpsScript. Expressions are used to perform computations and define values. An expression is a sequence of operators and operands.
Values
A value is a piece of data. That data can be a number, a string of text, a boolean (true or false), a character, or more complex data structure.
For example:
Var myVariable = 10
In this snippet, the literal value 10 is assigned to the variable myVariable. The identifier myVariable can now be used in various operations and calculations within the script. It can be compared with other values, or used to perform arithmetic operations, among other things.
Objects
Objects are entities that encapsulate data and behavior, often referred to as properties and methods, respectively. In OpsScript, objects allow you to organize and structure your code by grouping related data and functions together. Each object is associated with a type. The type defines the structure and behavior of the object.
Objects and values are closely related. Values represent simple, fundamental data structures such as numbers. Objects represent more complex data structures that often group together multiple related values.
Types
The type of a value or object refers to the category or classification of the data that the value or object represents. Each value and object has a type associated with it. Types define the characteristics and behaviors of values and objects, including what operations can be performed on them, and how they interact with other values and objects.
Operators
Operators are symbols or keywords that perform operations on one or more operands (values or expressions) to produce a result.
For example:
Var myVariable = 10 + 4
In this snippet, the literal values 10 and 4 are of the type Integer. They represent an integer number. Values of numeric types like Integer can use mathematical operators. 10 and 4 are added together using the addition operator (+) to produce the Integer value 14.
When an expression has multiple operators, the order in which they are evaluated is similar to the rules of precedence in mathematics. Parenthesis ( ) can be used to evaluate the expressions within them first.
Statements
Statements define the behavior and logic that govern how a script executes. Each statement typically performs a specific task, such as assigning a value to a variable or controlling the flow of a script. Statements often contain expressions as part of their functionality.
In previous examples, we have used the variable declaration statement. Let’s take a closer look:
Var myVariable = 10
In this snippet, the Var keyword is used to specify that we want to declare a variable for use in our script. Next, we provide an identifier: myVariable. Then we use the assignment operator = to specify that the initial value of our variable will be the following expression. Finally, we provide the expression that produces the value for our variable.
Let’s take a look at another example, the If statement. And If statement can be used to execute a block of code conditionally based on the value of an expression.
Var sales = 30000
Var bonus = 0
If sales > 10000 Then
bonus = 500
End If
In this snippet, we use an If statement to calculate a bonus amount based on sales. The If statement requires a condition. A condition is a boolean (true/false) expression. If the condition evaluates to true, the code following Then executes, otherwise it is skipped. In this example, bonus is set to 500 because the value of sales (30000) is greater than 10000. If sales were 10000 or less, bonus would remain at the initial value of 0.
Let’s look at a scenario where a smaller bonus is given if sales are less than or equal to 10000.
Var sales = 2000
Var bonus = 0
If sales > 10000 Then
bonus = 500
Else
bonus = 250
End If
In this snippet, because sales of 2000 is less than our threshold of 10000, the Else block and only the Else block of the If statement is executed. This results is bonus being set to 250.
Reference
Comments
Comments are non-executable text annotations within the script that are ignored during execution. They are used to provide explanations, documentation, and make it more readable for others or for future reference. OpsScript supports two types of comments:
Single-Line Comments: Single-line comments begin with the // characters and continue until the end of the line. They are used to annotate a single line of code.
// This is a single-line comment
Multi-Line Comments: Multi-line comments begin with /* and end with */. They can span multiple lines and are often used for longer explanations or for commenting out entire blocks of code.
/*
* This is a multi-line comment
* It can span multiple lines
* Useful for providing detailed explanations
*/
Statements
Return Statement
The Return statement is used to explicitly exit the currently executing script, rule or function and produce a result. Use Return for early termination of a script. Use return on rules and functions to terminate and produce a result. You may have multiple Return statements, but only one Return statement can be executed.
Return
Immediately stops execution of the script.
Return expression
expression: The value to return. This can be any valid expression that evaluates to the appropriate data type.
Immediately stops execution of the current rule or function and returns a value to the caller.
Assignment Statement
The assignment statement is used to assign a value to a variable or a property. It allows you to store and manipulate data by associating a value with a specific identifier. The assignment statement is a fundamental concept in OpsScript programming, allowing you to manipulate data by associating values with variables and properties. It forms the basis of variable initialization and data manipulation. The assignment operator = is used to assign values. It should not be confused with the comparison operator == used to compare values for equality.
target = value
target: The variable or property to which the value is being assigned.
value: The expression or literal value being assigned to the target.
Constant Declaration
A constant declaration is used to define a named constant with a fixed value. Constants are variables whose values cannot be changed once they are defined. They are typically used for values that are known ahead of time and are not expected to change during the execution of the script.
Constants are typically declared at the top of a script or in a specific section dedicated to defining constants. They provide meaningful names for fixed values used throughout the script, making the code more readable and maintainable.
Const constant_name = value
Const: Keyword used to declare a constant.
constant_name: The name of the constant being declared. Must begin with a letter and can be followed by letters, numbers and the underscore character.
value: The value assigned to the constant. This can be any valid expression that evaluates to a constant value.
Variable Declaration
A variable declaration is used to create a new variable and initialize it with a value. Variables are placeholders for storing data that can be manipulated and referenced throughout the script.
Var variable_name = value
Var: Keyword used to declare a constant.
variable_name: The name of the variable being declared. Must begin with a letter and can be followed by letters, numbers and the underscore character.
You set the variable value when the variable is initially declared but it can be changed throughout the script based on the logic of the script.
You use a variable when you know you are going to change the value based on the logic of the script.
value: The value assigned to the variable. This can be any valid expression.
If Statement
The If statement is a control flow statement used to execute a block of code conditionally based on the evaluation of a specified condition. It allows you to implement decision-making logic within your scripts.
Variables declared within the If statement block are scoped to that block and are only accessible within it.
Basic
If condition Then
// Code to execute if the condition is true
End If
If: Keyword used to declare the start of an If statement.
condition: An expression that evaluates to a boolean value (true or false)
Then: Keyword that marks the beginning of the black of code to execute if the condition is true.
End If: Marks the end of the If statement.
All Rules contain some form of If Then Logic. You kick it off by typing If
Every If Statement must start with an If and end in an End If to close.
If Then is a basic comparison.
If This.Response.Value == True Then
This.Response.Score = This.Questions.PossibleScore
End If
Else is the catch-all statement and handles all remaining use cases.
If This.Response.Value == True Then
This.Response.Score = This.Questions.PossibleScore
Else
This.Response.Score = 0
End If
If Then Else If
If This.Response.Value == True Then
This.Response.Score = This.Questions.PossibleScore
Else If This.Response.Value == False Then
This.Response.Score = 0
Else
Return This.Pass()
End If
The condition specified in the If statement is evaluated. If the condition evaluates to true, the block of code enclosed between Then and End If is executed. If the condition evaluates to false, the block of code is skipped, and execution continues with the next statement after the End If.
Optional Else Clause:
You can include an optional Else block to specify what code should be executed if the condition evaluates to false.
If condition Then
// Code to execute if the condition is true
Else
// Code to execute if the condition is false
End If
Multiple Conditions with Else If
You can chain multiple conditions together using Else If to evaluate different conditions sequentially.
If condition1 Then
// Code to execute if condition1 is true
Else If condition2 Then
// Code to execute if condition1 is false and condition2 is true
Else
// Code to execute if both condition1 and condition2 are false
End If
ForEach Statement
The ForEach statement is used to iterate over elements in a collection, such as an array or a list. It allows you to perform a specified action for each element in the collection. It's commonly used to process lists of items and perform specific operations, such as calculations, transformations, or data processing.
ForEach element In collection
// Code to execute for each element
Next
element: A variable that represents each individual element in the collection during each iteration.
collection: The collection over which to iterate. This can be an array, a list, or any other iterable data structure.
The ForEach statement iterates over each element in the specified collection. During each iteration, the element variable is assigned the current element being processed, and the code block within the ForEach loop is executed. After processing all elements in the collection, the execution continues with the statement following the Next keyword.
Continue Statement
The Continue statement is used within a ForEach loop to skip the current iteration and continue with the next iteration of the loop. It allows you to bypass the remaining code within the loop for the current element and move on to the next element in the collection.
ForEach element IN collection
If condition Then
Continue
End If
// Code to execute if condition is false
Next
The Continue statement affects only the current iteration of the loop. After executing Continue, the loop proceeds to the next iteration, and subsequent iterations are not affected.
Break Statement
The Break statement is used within a ForEach loop to immediately terminate the loop and exit its execution. It allows you to prematurely end the loop iteration based on certain conditions, without completing all iterations of the loop.
ForEach element In collection
If condition Then
Break
End If
// Code to execute if condition is false
Next
Expressions
This Keyword
The This keyword refers to the context of the currently running rule or script. The data and methods provided by This varies depending on the purpose of the rule or script.
Example Question Response Rule:
Var currentQuestionId = This.Question.Id
In this example, the ID of the current question is assigned to the currentQuestionId variable. The value of This is set by the platform when the rule is evaluated.
The This keyword is an important feature of rules and script. It allows you to create powerful behaviors based on decisions made using dynamic information in the platform.
Literal Expression
Literal expressions in OpsScript represent fixed values written directly in the code. They are constant values that do not require computation or evaluation and are used to represent data directly within the script. Literal expressions can represent various data types, such as numbers, strings, booleans.
Numeric Literals
Var age = 30 // Integer literal
Var pi = 3.14 // Decimal literal
Text Literals
Var message = "Hello, world!" // String literal
Var letter = 'H' // Character literal
Text always has to be in between quotations.
Boolean Literal
Var isTrue = true
Var isFalse = false
Null Literal
Null
Member Access
Objects in OpsScript can have properties, which are variables associated with the object, and methods, which are functions associated with the object. Member access allows you to retrieve or manipulate these properties and call methods of an object.
object.property
or
object.method(argument1, argument2)
object: The object from which you want to access the property or method.
property: The name of the property you want to access.
method: The name of the method you want to call.
argument: Optional arguments to supply the method to call if applicable.
OpsScript also supports nested member access, allowing you to access properties or methods of objects nested within other objects.
object.property1.property2.property3
Object Creation
The New operator is used to create a new instance of an object or a data structure. It allows you to allocate memory for the object and initialize its properties or fields.
New object_type(parameters)
object_type: The type of object or data structure to be created.
parameters: Optional parameters passed to the constructor of the object or data structure, if applicable. A comma separated list of parameters is used to specify multiple parameters.
In the following example we create a new date object and assign it to a variable.
Var event = New DateTime(2050, 6, 2, 10, 30, 0)
The DateTime type has multiple constructors available. We have selected the one that allows us to provide a date and time. The event variable is assigned our new DateTime object with a value that represents June 6th in the year 2050 at 10:30 AM.
List Initialization
List initialization involves creating a list and initializing it with a predefined set of elements.
New list_type() { element1, element 2}
list_type: The type of list to be created. This can be any list type.
element: A list of expressions whose value will be added to the list as it is created.
In the following example we create a new List of Integers and populate it with even numbers under 10.
Var evenNumbers = New List<Integer>() { 2, 4, 6, 8 }
If elements were not specified, the list would be empty. Elements would have to be added to the list one at a time using the Add method on the list. List initialization provides a concise way to initialize a list with values.
If Expression
The if expression, also known as the conditional expression or ternary if expression, provides a concise way to express conditional logic in a single line. It's particularly useful when you want to assign a value based on a condition without writing a full if-else statement. The ternary if expression is a shorthand for expressing simple conditional logic.
While the If expression is similar to the If statement, the If expression is better suited for simple conditional scenarios.
If(condition, expression_if_true ,expression_if_false)
condition: The expression or condition to evaluate.
expression_if_true: The value to return if the condition evaluates to true.
expression_if_false: The value to return if the condition evaluates to false.
Example:
Var number = 5
Var numberSize = If(number < 100, "The number is small", "The number is large")
In this snippet, numberSize is assigned the string “The number is small”.
It's important to keep the ternary if expression simple and easy to understand. Complex logic may be better expressed using traditional If-Else statements for clarity.
If Null Expression
The if null expression, also known as the null coalescing expression, allows you to handle null values more effectively. This operator simplifies the code required to handle null values, making it more concise and readable. It's particularly handy in scenarios where you need to provide a fallback value or handle optional values gracefully without resorting to verbose conditional logic. By handling null values appropriately, you ensure that your script behaves as expected and produces accurate results.
If(nullable_value, default_value)
nullableValue: is the variable or expression that may be null.
defaultValue: is the value that will be used if nullableValue is null.
Logical Expressions
Logical expressions are used to evaluate conditions and produce boolean values (true or false) based on the outcome of those conditions. They are essential for making decisions and controlling the flow of execution within a program. OpsScript provides several logical operators that allow you to combine and manipulate boolean values and expressions.
Equality and Inequality
The equality operator == checks if two values are equal, returning true if they are, and false otherwise. Take care not to confuse the equality operator == with the assignment operator =. The inequality operator != checks if two values are not equal, returning true if they are not, and false otherwise.
Var result1 = x == y // true if x is equal to y
Var result2 = x != y // true if x is not equal to y
Greater Than and Less Than
The greater than operator > checks if the left operand is greater than the right operand, returning true if it is, and false otherwise. The less than operator < checks if the left operand is less than the right operand, returning true if it is, and false otherwise.
Var result3 = x > y // true if x is greater than y
Var result4 = x < y // true if x is less than y
Greater Than or Equal To and Less Than or Equal To
The greater than or equal to operator >= checks if the left operand is greater than or equal to the right operand, returning true if it is, and false otherwise. The less than or equal to operator <= checks if the left operand is less than or equal to the right operand, returning true if it is, and false otherwise.
Var result5 = x >= y // true if x is greater than or equal to y
Var result6 = x <= y // true if x is less than or equal to y
AndAlso
Returns true if both operands are true, otherwise, it returns false. The second operand is evaluated only if the first returns true.
Var result = x > 0 AndAlso y < 10
OrElse
Returns true if at least one of the operands is true, otherwise, it returns false. The second operand is evaluated only if the first return false.
Var result = x == 0 OrElse Y == 0
Not
The logical NOT operator (also called the negation operator) negates the value of its operand, returning true if the operand is false, and false if the operand is true.
Var result = Not x > 10
Logical expressions are commonly used in conditional statements (such as If statements) to determine the flow of execution based on certain conditions. They can also be used to filter data, control loops, and make decisions in various programming contexts.
Increment and Decrement Expressions
Prefix and postfix increment operators are both used to increase the value of a variable by 1, but they do so in different ways regarding when the increment actually occurs in relation to the variable's use within an expression.
Prefix Increment Operator
The variable is incremented first, and then the updated value is used in the expression or assignment.
++variable
Postfix Increment Operator
The current value of the variable is used first, and then it is incremented afterward.
variable++
Prefix and postfix decrement operators are similar to their increment counterparts but perform decrement operations (decreasing the value of a variable by 1) instead of incrementing. However, they exhibit the same behavior regarding when the decrement actually occurs in relation to the variable's use within an expression.
Prefix Decrement Operator
The value of the variable is decremented before its current value is used in the expression.
--variable
Postfix Decrement Operator
The value of the variable is used in the expression or assignment first, and then it is decremented.
variable--
Lambda Functions
Lambdas define small, inline pieces of code. They are used in scenarios where you need to pass behavior as an argument to another method.
Function Operators
Not: negates a Bool (It turns a true into a false and false into a true)
As: Defines what type a variable is - Operator that is defining the type or As can be used to make a type
Any: on a list you have the option of Any() - Any means anything in the list, if anything exists it returns a Pass. It goes through the entire list 1 at a time and runs the function and will continue until it gets a true or it will return a false.
All: is the opposite of Any, it requires all list items to pass to return a true and if any fail it returns a fail.
Ienumerable: any kind of list
Return: is a statement, it evaluates the statement after it. It returns the rule result.
ElementAt: is an indexed list and all indexes start at 0.
If you want the 12th item it is really the 11th in the list.
Function Predicates
Where: As iEnumerable means it returns a list and the condition reduces the size of the list.
It’s just a list
FirstOrDefault: First use case of the condition but it will return a default value if the condition isn’t met and it won’t fail
Any: Any item in the list meets the condition returns True or False
All: All the items in the list have to meet the condition (wouldn’t use this as much) returns True or False
Contains: Does this list contain this condition that returns True False (don’t use it that much)
StartsWith: Only available with Strings and returns true false if an item on a list starts with.
Arrays, Lists, IEnumerable
IEnumerable: any kind of list
Difference between an array and a list: you can change the amount of items in a list, where as you cannot change the amount of items in an array.
You can change the items in an array.
Single-Line Function
Function(argument AS argument_type) expression
Function: This keyword indicates the beginning of a lambda function.
argument AS argument_type: This part specifies the argument(s) that the lambda function takes. argument is the name of the argument, and argument_type is its type. You can define multiple arguments separated by commas.
expression: This is the expression that the lambda evaluates to. It can be any valid OpsScript expression.
Example:
// Define a list of numbers
Var numbers = new List<Int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
Var evenNumbers = numbers.Where(Function(x As Int) x Mod 2 == 0)
In this example:
numbers is a list containing numbers from 1 to 10.
numbers.Where(...) applies the where function to the numbers list.
Function(x As Int) x Mod 2 == 0 is a lambda function that takes each element x from the list and checks if it is even (i.e., divisible by 2 with no remainder).
The where function filters the elements from the numbers list based on the condition specified in the lambda. For each element in the list, the lambda function is invoked. The lambda function takes the current element as its argument and evaluates to either true or false based on the condition specified inside the lambda. If the lambda function evaluates to true for a particular element, that element is included in the resulting list. If it evaluates to false, the element is excluded.
The resulting list evenNumbers contains only the even numbers from the original list.
Multi-line Function
Function(argument as argument_type)
// Code to evaluate
Return result_expression
End Function
Function: This keyword indicates the beginning of a lambda function.
argument AS argument_type: This part specifies the argument(s) that the lambda function takes. argument is the name of the argument, and argument_type is its type. You can define multiple arguments separated by commas.
result_expression: This is the expression that the lambda evaluates to. It can be any valid OpsScript expression.
End Function: This keyword indicates the end of a multi-line lambda function.
Example:
Var names = new List<String>() { "Alice", "Bob", "Carl" }
Var superHeroes = names.Select(Function(x As String)
var superName = "Super" + x
Return superName
End Function)
In this example:
names is a list of people’s names.
names.Select(...) applies the select function to the numbers list.
Function(x As String)... is a lambda function that takes each element x from the list and performs a transformation on the element.
The select function is used to transform each element of the names list into a new form. The lambda function defines the transformation to be applied to each element of the names list. For each element in the list, the lambda function is invoked. The lambda function takes the current element as its argument, creates a new variable superName whose value is the name with the string “Super” prepended to it, and finally returns the new name.
The variable superName is defined within the lambda function. Variables declared within a lambda function are local to that lambda. They are not accessible from outside the lambda function. When a lambda function is executed multiple times, the value of local variables is not available in subsequent executions.
The resulting list is the names from the original list with “Super “ prepended to each name: SuperAlice, SuperBob, SuperCarl.