Currently, the Calculated Model Sample app only calculates the count of the records for each Type. I would like to calculate the sum of the ratings for each Type as well.
To briefly explain the app's data model, there are three fields for each record: Name (str), Type (str), and Rating (num).
I have added a sum field to the Aggregation calculated model, but am unclear what exactly I need to change in the code CalculatedModels script in the app.
Here is the code block which calculates the count of each Type. I've added the records.Sum = to indicate how and where the sum should be recorded. However, since the existing for loop increments by 1 (to calculate the count), do I need another for loop that would increment by the value of each record's Rating (since the sum will be the total of the Ratings for each Type? Or can I just use the existing for loop, as I have indicated by inserting the records.Sum = where I did?
/**
* Gathers statistics of Data records distribution by Type field values.
* Used by the calculated datasource AggregationByType.
* @return {Array<Aggregation>} array of records with the stats by Type.
*/
function getStatisticsByType_() {
var allRecords = app.models.Data.newQuery().run();
var stats = {};
for (var i = 0; i < allRecords.length; i++) {
var recordType = allRecords[i].Type;
if (!stats[recordType]) {
stats[recordType] = 0;
}
stats[recordType]++;
}
var records = [];
var properties = Object.getOwnPropertyNames(stats);
for (var j = 0; j < properties.length; j++) {
var record = app.models.Aggregation.newRecord();
record.Name = properties[j];
record.Count = stats[properties[j]];
record.Sum =
records.push(record);
}
records.sort(sortDataByName_);
return records;
}