Data Processing
a-calc excels at data processing, reporting, and analytics.
Table Calculations
Row Calculations
javascript
import { calc } from "a-calc";
const tableData = [
{ product: "A", price: 100, quantity: 5, discount: 0.9 },
{ product: "B", price: 200, quantity: 3, discount: 0.85 },
{ product: "C", price: 150, quantity: 8, discount: 0.95 },
];
const withSubtotal = tableData.map((row) => ({
...row,
subtotal: calc("price * quantity * discount | =2", row),
}));
// subtotals: ['450.00', '510.00', '1140.00']Column Aggregation
javascript
import { calc_sum } from "a-calc";
const salesData = [
{ month: "Jan", revenue: 100000, cost: 60000 },
{ month: "Feb", revenue: 120000, cost: 70000 },
{ month: "Mar", revenue: 150000, cost: 85000 },
];
const summary = {
totalRevenue: calc_sum("revenue | ,", salesData), // '370,000'
totalCost: calc_sum("cost | ,", salesData), // '215,000'
totalProfit: calc_sum("revenue - cost | ,", salesData), // '155,000'
};Percentage Share
javascript
import { calc, calc_sum } from "a-calc";
const categoryData = [
{ category: "Electronics", sales: 50000 },
{ category: "Clothing", sales: 30000 },
{ category: "Food", sales: 20000 },
];
const total = calc_sum("sales", categoryData);
const withPercentage = categoryData.map((item) => ({
...item,
percentage:
calc("sales / total * 100 | ~5=2", { sales: item.sales, total }) + "%",
}));
// ['50.00%', '30.00%', '20.00%']Growth Rate
javascript
import { calc } from "a-calc";
const monthlyData = [
{ month: "Jan", value: 10000 },
{ month: "Feb", value: 12000 },
{ month: "Mar", value: 11500 },
{ month: "Apr", value: 15000 },
];
const withGrowth = monthlyData.map((item, index) => {
if (index === 0) return { ...item, growth: "-" };
const prev = monthlyData[index - 1].value;
const growth = calc("(current - prev) / prev * 100 | ~5=2", {
current: item.value,
prev,
});
return { ...item, growth: growth + "%" };
});
// growth: ['-', '20.00%', '-4.17%', '30.43%']Unit Conversion
javascript
import { calc } from "a-calc";
function formatBytes(bytes) {
if (calc(`${bytes} < 1024 | !n`)) return bytes + " B";
if (calc(`${bytes} < 1048576 | !n`))
return calc("bytes / 1024 | ~5=2", { bytes }) + " KB";
if (calc(`${bytes} < 1073741824 | !n`))
return calc("bytes / 1048576 | ~5=2", { bytes }) + " MB";
return calc("bytes / 1073741824 | ~5=2", { bytes }) + " GB";
}
formatBytes(1536); // '1.50 KB'
formatBytes(1572864); // '1.50 MB'
formatBytes(1610612736); // '1.50 GB'Batch Processing with calc_wrap
javascript
import { calc_wrap } from "a-calc";
const data = [
{ a: 10, b: 20 },
{ a: 30, b: 40 },
{ a: 50, b: 60 },
];
const calcSum = calc_wrap("a + b | =2");
const calcProduct = calc_wrap("a * b | =2");
const calcRatio = calc_wrap("a / b * 100 | ~5=2");
const results = data.map((item) => ({
...item,
sum: calcSum(item),
product: calcProduct(item),
ratio: calcRatio(item) + "%",
}));