@adaptabletools/adaptable
Version:
Powerful AG Grid extension which provides advanced, cutting-edge functionality to meet all DataGrid requirements
49 lines (48 loc) • 1.84 kB
JavaScript
import { toNumber } from '../../Utilities/Extensions/NumberExtensions';
const getNumericValue = (input) => {
if (typeof input === 'number') {
return input;
}
const numericValue = toNumber(input);
return isNaN(numericValue) ? null : numericValue;
};
export const weightedAverage = (params, columnId, weightColumnId) => {
const { api: gridApi, rowNode: groupRowNode, values } = params;
let weightedValueSum = 0;
let totalWeight = 0;
const childNodes = getMatchingChildNodes(groupRowNode, values.length);
for (let i = 0; i < values.length; i++) {
const value = values[i];
if (value != null && typeof value === 'object') {
weightedValueSum += value[columnId] ?? 0;
totalWeight += value[weightColumnId] ?? 0;
}
else {
const childNode = childNodes[i];
if (!childNode) {
continue;
}
const columnValue = getNumericValue(value);
const weightValue = getNumericValue(gridApi.getCellValue({ colKey: weightColumnId, rowNode: childNode }));
if (weightValue !== null) {
totalWeight += weightValue;
}
if (columnValue !== null && weightValue !== null) {
weightedValueSum += columnValue * weightValue;
}
}
}
const result = totalWeight !== 0 ? weightedValueSum / totalWeight : 0;
return {
toString: () => String(result),
toNumber: () => result,
[columnId]: weightedValueSum,
[weightColumnId]: totalWeight,
};
};
function getMatchingChildNodes(groupRowNode, valueCount) {
if (groupRowNode.childrenAfterFilter?.length === valueCount) {
return groupRowNode.childrenAfterFilter;
}
return groupRowNode.childrenAfterGroup ?? [];
}