Writing Calculators - abrice/dz GitHub Wiki

Calculators are javascript functions

Calculators are javascript functions that return a value. As a function they receive as input the current row of data and they return a single value back. That value is then stored in the column for the current row.

Importantly, Functions are applied before filters and groupings so the function will be called one time for every row of the original data.

  • If there is no code in the function then nothing is returned so the column value will be empty

  • In basic form, a value can be returned:

    return 100;

  • Or a calculation is possible:

      return 100 + 10;
    
  • Or a field value can be returned. Note that it doesn't have to be the field for the current column. All preceding columns are available:

      return d("field1"); 
    
  • Or a calculation on a field value can be returned:

      return +d("field1")/100;
    
  • Or complex calculations are possible with the result being returned.

      var returnvalue = +d("field1") * +d("field2");
      return returnvalue;
    

the text "field1" and "field2" would be the fieldnames you have used for the columns.

Functions can be used on text fields as well as number fields:

  • A value to text conversion can be returned. So assuming field1 is one of 0,1,2 then:

      var t = ["Red","Amber","Green"];
      return t[+d("field1")];
    

will return "Amber" if field1 = 1

  • Any javascript string function is available:

      return d("field1").sub(3,3);
    

would return three middle characters from the string in field1.

Accessing fields

Fields can be accessed either:

  • By their fieldname in the form d("fieldname"] That includes the quotes and the brackets
  • By the field index in the form d([x]) where x is the numeric index of the column in the set of all columns

Trying out a function

The function is tested against the first row of the full data on [Apply]. If it fails then it is ignored.