Dev.to WebDev 🛠 Dev 👁 0 📖 1 min read

How Progressive Slab Calculators Work (with a JavaScript Example)

Tax and utility calculators look simple from the outside, but most of them share one idea: progressive slabs. Pakistan's income tax and electricity tariffs both work this way, and it is a nice small problem to code.

Tax and utility calculators look simple from the outside, but most of them share one idea: progressive slabs. Pakistan's income tax and electricity tariffs both work this way, and it is a nice small problem to code.

The idea

A slab table says: income up to A is taxed at 0%, the part between A and B at r1, the part between B and C at r2, and so on. The common mistake is applying one rate to the whole amount. You have to tax each slice separately.

A minimal JavaScript version

The numbers below are example slabs only, not official rates:

const slabs = [
  { upTo: 600000, rate: 0 },
  { upTo: 1200000, rate: 0.05 },
  { upTo: 2200000, rate: 0.15 },
  { upTo: Infinity, rate: 0.25 },
];

function progressiveTax(income) {
  let tax = 0, lower = 0;
  for (const { upTo, rate } of slabs) {
    if (income <= lower) break;
    const slice = Math.min(income, upTo) - lower;
    tax += slice * rate;
    lower = upTo;
  }
  return Math.round(tax);
}

console.log(progressiveTax(1800000));

Things real calculators add

  • Monthly vs yearly input: convert monthly salary to annual before applying slabs
  • Fixed amounts per slab: many official tables express each slab as a fixed amount plus a percentage of the excess, which is the same maths written differently
  • Rate tables per year: budgets change the slabs, so keep them in data, not code
  • Rounding rules that match the official method

Electricity bills use the same slice-by-slice idea on units instead of rupees, plus fixed charges and taxes on top.

See it in a real tool

If you want to compare your output with a working calculator, BaKhabar Pakistan's income tax calculator uses this kind of slab logic for salaried income, and its electricity bill calculator applies it to units.

It is a good beginner exercise: write the function, then write tests for the slab edges (exactly at A, just above A), because that is where bugs hide.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.