Skip to content
This repository has been archived by the owner on Jan 21, 2022. It is now read-only.

Plan snippets

Hristo Iliev edited this page Oct 17, 2017 · 4 revisions

Calculate the average sum of all measures

Abacus does not support average out of the box, but this is easily implemented keeping the sum and the count of elements in compound object. This also increases the accuracy of the result.

Average sum plan
{ 
  plan_id: 'average_value', 
  measures: [{ 
    name: 'store', 
    unit: 'BYTE' 
  }], 
  metrics: [{ 
    name: 'store', 
    unit: 'GIGABYTE', 
    type: 'discrete', 
    meter: (m) => new BigNumber(m.warm_store).div(1073741824).toNumber(),
    accumulate: (a, c, start, end, from, to, twCell) => a ? 
        { sum: a.sum + c, count: a.count + 1, avg: (a.sum + c) / (a.count + 1) } : 
        { sum: c, count: 1, avg: c }
  }]
}

Count of several metrics

Here we are summing several kind of transactions (charges, refunds, others) into individual metrics. Then we have a global sum transactions that counts the number of all operations. We want to keep a breakdown of the individual components, plus the total count of operations.

Sum of all transactions
{
  plan_id: 'transactions-plan',
  measures: [
    {
      name: 'charges',
      unit: 'NUMBER'
    },
    {
      name: 'refunds',
      unit: 'NUMBER'
    },
    {
      name: 'others',
      unit: 'NUMBER'
    }
  ],
  metrics: [{
    name: 'transactions',
    unit: 'NUMBER',
    type: 'discrete',
    meter: (m) => ({
      charges: new BigNumber(m.charges || 0).toNumber(),
      refunds: new BigNumber(m.refunds || 0).toNumber(),
      others: new BigNumber(m.others || 0).toNumber()
    }),
    accumulate: (a, c) => {
      const charges = a ? new BigNumber(a.charges).add(c.charges) : c.charges
      const refunds = a ? new BigNumber(a.refunds).add(c.refunds) : c.refunds;
      const others = a ? new BigNumber(a.others).add(c.others) : c.others;
      
      const transactions = a ?
        a.transactions.add(charges).add(refunds).add(others) :
        new BigNumber(0).add(charges).add(refunds).add(others);

      return {
        charges: charges.toNumber(),
        refunds: refunds.toNumber(),
        others: others.toNumber(),
        transactions: transactions.toNumber()
      };
    }
  }]
}
Clone this wiki locally