Groovy Google Chart Encoding Script

Home / Blog / Java / Grails / Groovy Google Chart Encoding Script

I’ve been playing around with Google Chart integration into a new Grails application, and while teaching myself the chart data formats, I converted the javascript data encoding script to Groovy. This hasn’t been tested thoroughly, but its been working nicely for me in my project.


/**
* See http://code.google.com/apis/chart/docs/data_formats.html#extended
*/
class GoogleChartUtil {

private static final String simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

// This function scales the submitted values so that
// maxVal becomes the highest value.
static simpleEncode(valueArray,maxValue) {
def chartData = ['s:'];
for (int i = 0; i < valueArray.size(); i++) { def currentValue = valueArray[i]; if (currentValue >= 0) {
chartData.push(simpleEncoding.charAt((int) Math.round((simpleEncoding.length()-1) *
currentValue / maxValue)));
}
else {
chartData.push('_');
}
}
return chartData.join('');
}

private static final String purchase yasmin EXTENDED_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.';
private static final int EXTENDED_MAP_LENGTH = EXTENDED_MAP.length();

static extendedEncode(arrVals, maxVal) {
def chartData = 'e:';

int len = arrVals.size();
for(int i = 0; i < len; i++) { // In case the array vals were translated to strings. def numericVal = new Float(arrVals[i]); // Scale the value to maxVal. def scaledVal = Math.floor(EXTENDED_MAP_LENGTH * EXTENDED_MAP_LENGTH * numericVal / maxVal); if(scaledVal > (EXTENDED_MAP_LENGTH * EXTENDED_MAP_LENGTH) - 1) {
chartData += "..";
} else if (scaledVal < 0) { chartData += '__'; } else { // Calculate first and second digits and add them to the output. def quotient = Math.floor(scaledVal / EXTENDED_MAP_LENGTH); def remainder = scaledVal - EXTENDED_MAP_LENGTH * quotient; chartData += EXTENDED_MAP.charAt((int)quotient) + EXTENDED_MAP.charAt((int)remainder); } } return chartData; } }

Leave a Comment