Variance Function
Goal:
Calculate a variance from numbers inserted to Text Inputs in a Document or Bundled Documents.
Instructions:
- Create the Template tag Variance and attach this tag to all Text Inputs in your Template that should be calculated.
- Create the Template tag GetVarianceValue and attach this tag to the Text Input in your Template where the sum amount should be inserted.
- Insert the below-mentioned script to the Variance tag.
Script Example:
var finder = LEGITO.documentBuilder.event.createElementFinder(); var modeValues = finder.findElementsByTagsAuto(Tags);
const Results = LEGITO.documentBuilder.getTagsByName("GetVarianceValue"); var resultElement = finder.findElementsByTagsAuto(Results)[0];
let valuesArray = [] for(var i in modeValues) { if(modeValues[i].getValue() !== null) { valuesArray.push(parseInt(modeValues[i].getValue(), 10)); } }
const getNumWithSetDec = function( num, numOfDec ){ Â Â Â Â var pow10s = Math.pow( 10, numOfDec || 0 ); Â Â Â Â return ( numOfDec ) ? Math.round( pow10s * num ) / pow10s : num; };
const getAverageFromNumArr = function( numArr, numOfDec ){ Â Â Â Â var i = numArr.length, Â Â Â Â Â Â Â Â sum = 0; Â Â Â Â while( i-- ){ Â Â Â Â Â Â Â Â sum += numArr[ i ]; Â Â Â Â } Â Â Â Â return getNumWithSetDec( (sum / numArr.length ), numOfDec ); };
const getVariance = function( numArr, numOfDec ){ Â Â Â Â var avg = getAverageFromNumArr( numArr, numOfDec ), Â Â Â Â Â Â Â Â i = numArr.length, Â Â Â Â Â Â Â Â v = 0; Â
    while( i-- ){         v += Math.pow( (numArr[ i ] - avg), 2 );     }     v /= numArr.length;     return getNumWithSetDec( v, numOfDec ); };
resultElement.setValue(getVariance(valuesArray, 2).toString()); |