nodedb-json
Version:
A lightweight JSON-based database for Node.js with TypeScript support, indexing, and complex query capabilities
60 lines • 2.14 kB
JavaScript
import _ from 'lodash';
export function applyAggregation(data, aggregations) {
return aggregations.map(agg => {
switch (agg.type) {
case 'count':
return {
type: 'count',
value: data.length
};
case 'sum':
if (!agg.field) {
throw new Error('Sum aggregation requires a field');
}
return {
type: 'sum',
field: agg.field,
value: _.sumBy(data, agg.field)
};
case 'avg':
if (!agg.field) {
throw new Error('Average aggregation requires a field');
}
return {
type: 'avg',
field: agg.field,
value: _.meanBy(data, agg.field)
};
case 'min':
if (!agg.field) {
throw new Error('Min aggregation requires a field');
}
return {
type: 'min',
field: agg.field,
value: _.get(_.minBy(data, item => _.get(item, agg.field)), agg.field, 0)
};
case 'max':
if (!agg.field) {
throw new Error('Max aggregation requires a field');
}
return {
type: 'max',
field: agg.field,
value: _.get(_.maxBy(data, item => _.get(item, agg.field)), agg.field, 0)
};
case 'group':
if (!agg.groupBy) {
throw new Error('Group aggregation requires a groupBy field');
}
return {
type: 'group',
groupBy: agg.groupBy,
value: _.groupBy(data, agg.groupBy)
};
default:
throw new Error(`Unsupported aggregation type: ${agg.type}`);
}
});
}
//# sourceMappingURL=aggregator.js.map