Skip to content

Aggregation Functions

Five functions for batch calculations over data arrays.

Functions

FunctionDescription
calc_sumSum all results
calc_avgAverage of all results
calc_maxMaximum result
calc_minMinimum result
calc_countCount truthy (non-zero) results

Signature

typescript
function calc_sum(expr: string, dataArray: object[]): string;
function calc_avg(expr: string, dataArray: object[]): string;
function calc_max(expr: string, dataArray: object[]): string;
function calc_min(expr: string, dataArray: object[]): string;
function calc_count(expr: string, dataArray: object[]): string;

Examples

javascript
import { calc_sum, calc_avg, calc_max, calc_min, calc_count } from "a-calc";

const items = [
  { a: 1, b: 2 },
  { a: 3, b: 4 },
  { a: 5, b: 6 },
];

calc_sum("a + b", items); // '21'
calc_avg("a + b", items); // '7'
calc_max("a + b", items); // '11'
calc_min("a + b", items); // '3'
calc_count("a", items); // '3'

With Formatting

javascript
const orders = [
  { price: 99.9, qty: 2 },
  { price: 49.9, qty: 1 },
  { price: 29.9, qty: 3 },
];

calc_sum("price * qty | =2,", orders); // '339.40'
calc_avg("price | =2", orders); // '59.90'

Edge Cases

javascript
calc_sum("value", []); // '0'
calc_avg("value", []); // '0'

// Error in any element returns the error value
calc_sum("a / b", [
  { a: 10, b: 2 },
  { a: 5, b: 0 },
]); // '-'

Real-World Example

javascript
const employees = [
  { base: 8000, bonus: 2000, deduction: 500 },
  { base: 10000, bonus: 3000, deduction: 800 },
  { base: 12000, bonus: 4000, deduction: 1000 },
];

calc_sum("base + bonus - deduction | =2,", employees); // '36,700.00'
calc_avg("base | =0", employees); // '10000'
calc_max("base + bonus", employees); // '16000'
calc_min("base", employees); // '8000'
calc_count("bonus > 2000 ? 1 : 0", employees); // '2'

Released under the MIT License