Hi Rebecca,
As it was mentioned before, there are many ways to solve a problem. However, there's no need to use two separate functions that are basically doing the same thing. In this case, you only need a single function which will calculate the average of an unspecified number of parameters ("getAVG" is the name I've chosen for this function). The code you have, as it is right now, is restricted to seven variables; nothing more, nothing less. What would happen if tomorrow you have to create a form that requires ten or five variables? You'd have to rewrite the function, change the variable names, and change the number of variables. To solve this, a better approach would be to remove the document variables in the function and have them be declared in a watcher or a button. In that way, the function can be reused as many times as you need on as many forms as you want. By using getnargs() and getarg(), you can process as many variables as you need in a single function.
getnargs - Gets the number of arguments entered (7)
getarg - Gets the argument identified by the index you enter (running a FOR loop will loop through all of them)
//Function declaration
{
fn getAVG(){
local result = ""
local i = ""
local num = 0
local den = 0
//The for loop is gonna skip blank variables
for i = 1, i <= getnargs(), i = i + 1 do
if str(getarg(i)) <> "" then
num = num + val(str(getarg(i)))
den = den + 1
else "" endif
endfor
result = num/den
return result
}
}
Another precaution I took is the use of str() and val(str()). You can enter any type of argument (string or number) and the code won't crash because you are always converting them to the type you need.
*The reason why I'm wrapping val() around str() is because numbers cause val() to crash, but strings don't. Also, Str() can take both types of variables.
It's also worth mentioning that a key technique used by experienced developers is re-utilization. The code you create has to be reusable. By having only local variables, the above function can work on any form (not only those with BP variables).
The following code shows how to use the getAVG function.
//Code in button or watcher
DOCUMENT.SYSTOTAL = getAVG(DOCUMENT.SYSBP1,DOCUMENT.SYSBP2,DOCUMENT.SYSBP3,DOCUMENT.SYSBP4,DOCUMENT.SYSBP5,DOCUMENT.SYSBP6,DOCUMENT.SYSBP7...)
DOCUMENT.DIATOTAL = getAVG(DOCUMENT.DIABP1,DOCUMENT.DIABP2,DOCUMENT.DIABP3,DOCUMENT.DIABP4,DOCUMENT.DIABP5,DOCUMENT.DIABP6,DOCUMENT.DIABP7...)
Not only can you use getAVG for calculating the average of seven BP values, you could also use it to get the average of 1 or even 200 variables.
If you've got any questions, please let me know. I'm always happy to help.
Best,
Tomas Vazquez
Senior Developer – Team Lead
One Boston Place, Suite #2600 - Boston, MA 02108
D: (617) 390-8928 O: (617) 848-4488 F: (617) 996-1241
www.optumus.com – @optumus.com">cmcdonald@optumus.com
Posted : March 28, 2018 8:04 am