Fullscreen Image

Functions - JavaScript in Lucernex

JavaScript functions are supported in Lucernex. A function is a named set of statements that perform a task or calculate a value (Mozilla, 2020). The name given to a function can be used in multiple contexts within the same script. For example, you could apply the getNum function defined below to variable a, b, c, and so forth. The function itself wouldn't change and does not need to be repeated in full, but the function's results would depend on the variable it is associated with.

ClosedgetNum

This script converts any variable value regardless of data type to a number; for example, "$5.50" would be converted to 5.50. If the value cannot be converted to a number, the function returns 0.

In the code sample below, the code prior to the FUNCTIONS comment uses the getNum function twice, once on the invoice tax rate and once on the invoice total. The getNum function used is defined below the FUNCTIONS comment.

Copy
var valueToSet = 0;
var rate = getNum("${Issue.INV_TaxRate}");
var total = getNum("${Issue.INV_InvoiceTotal}");
 
// Calculate tax for invoice
valueToSet = total * rate;
 
///////////////////// FUNCTIONS /////////////////////
/*
* Take a variable of any type and return a number.
* If it is a number, return it as a number.
* If it can be represented as a number by removing non-numeric characters, return it as a number.
* Otherwise, return 0.
*/
function getNum(n) {
  if (n instanceof Number){ // if already a number, return it
    return n;
  }
 
  try {
    if (isNaN(n)){  // if not a valid number
      n = "" + n; // make sure n is a string
      n = n.replace(/\%|,|\$/gi, ""); // get rid of non-numeric chars
    }
    if (!isNaN(n)){ // if n is a valid number, return it
      return Number(n);
    }
  } catch(e){} // do nothing if there’s an error
 
  return Number(0); // always return 0 if we get to this point.
}

ClosedformatDate with getTwoCharForInt

Together, these two functions take the date result of a script and format it as a text value that Lucernex can convert to a date. These two functions are often used in reports.

Copy
// Takes a Date variable.
// Returns a String in MM/dd/yyyy format.
function formatDate(date) {
  return getTwoCharForInt(date.getMonth() + 1) + "/" +
         getTwoCharForInt(date.getDate()) + "/" + date.getFullYear();
}
 
function getTwoCharForInt(int) {
  return int < 10 ? "0" + int : "" + int;
}

ClosedclearTime

This function is used to clear the time component from a date field such as CreatedDate or ModifiedDate.

Copy
// Function to clear time component.
function clearTime(Date date) {​​
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);
  date.setMilliseconds(0);
}​​

ClosedisEmpty

This function is used to check whether a value exists and if it does, whether it has any content.

Copy
function isEmpty(str) {
  return (str == null) || (str.length == 0);
}