Inline Functions
Sometimes, you want a "formula" or "show if" expression to do really fancy stuff. Perhaps you want to do an "if/then/else" type of expression to decide whether a section of questions resolves to level 1 or level 2. It could be a lot more complicated than that (see the probability of readmission score for an example).
You will find that adding a simple if (x) { return y; }
won't work. For example, the following will not work:
(ScriptUtil.sum(mySection) > 5) return 2; else return 1;
The trick is that you need to define and execute a function inline, like this:
(function() { if (ScriptUtil.sum(mySection) > 5) return 2; else return 1; })()
Copy Rule
Technical Details
To break this this down, this part defines the function: (function() { if (ScriptUtil.sum(mySection) > 5) return 2; else return 1;})
and the ()
at the end simply runs the newly defined function.
Date Manipulations
You can create a new Date in Javascript using the new Date()
call, which returns the current date/time instant. You can use new Date(2020,2,10)
to create a date for March 10, 2020 (yes, March; the month is confusingly 0-indexed, so January is month 0).
You can call new Date().getMonth()
to get the current month (0-indexed again, so March is month 2).
To compare dates, simply subtract them to obtain the number of milliseconds in between, then divide that difference by 1000*60*60*24
to get the difference in days.
Google "Javascript date reference" for more information.
Advanced Javascript
As long your script evaluates to a single expression, you can do pretty much anything that you can do with Javascript. Some advanced scripting functionality uses an inline function as described above to have a complicated multi-line algorithm wrapped in a single expression.
You can learn more about Javascript using Google (e.g. "how do I compare dates in Javascript?") or by reading a good reference book (e.g. "Javascript: The Good Parts").