DEV Community

Cover image for Building a "fill any two boxes" calculator in plain JavaScript
Axarez
Axarez

Posted on

Building a "fill any two boxes" calculator in plain JavaScript

Most marketing calculators on the web solve one formula in one direction. A CPM calculator asks for spend and impressions and gives you CPM. If you already know your CPM and want the budget, you need a different tool, or a piece of paper.

We wanted one small widget that works in every direction: give it any two of the three values and it works out the third. Here is how that works in about 40 lines of plain JavaScript, with no framework.

The idea: three values, one relationship

Every one of these ad metrics is a single equation with three parts:

Metric Relationship
CPM cpm = cost ÷ impressions × 1000
CTR ctr = clicks ÷ impressions × 100
CPC cpc = cost ÷ clicks
ROAS roas = revenue ÷ cost

If you rearrange each one, you get a solver for every box. So the whole calculator is just a lookup table of three small functions per metric:

const QUICK = {
  cpm: {
    solve: {
      cpm:  v => v.cost / v.impr * 1000,
      cost: v => v.cpm * v.impr / 1000,
      impr: v => v.cost / v.cpm * 1000
    }
  },
  roas: {
    solve: {
      roas:    v => v.revenue / v.cost,
      revenue: v => v.roas * v.cost,
      cost:    v => v.revenue / v.roas
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

Which box should we solve?

This is the only interesting part. When someone types, we need to decide which box is the "answer". The rule that feels natural is: the two boxes you touched most recently are your inputs, and the third one is the answer.

So we keep a tiny history of edited fields:

const order = [];

function onInput(e) {
  const k = e.target.dataset.k;
  const i = order.indexOf(k);
  if (i > -1) order.splice(i, 1);       // move it to the end
  if (e.target.value.trim()) order.push(k);

  const v = readValues();               // { cost: 500, impr: 100000, cpm: NaN }
  const given = order.filter(x => v[x] > 0).slice(-2);
  if (given.length < 2) return showHint('Fill in any two boxes.');

  const target = keys.find(x => !given.includes(x));
  const result = metric.solve[target](v);
  writeBox(target, result);
}
Enter fullscreen mode Exit fullscreen mode

If you type spend and impressions, CPM fills in. If you then change CPM, spend and CPM become the two most recent, so impressions are recalculated instead. Nobody has to press a "solve for" button.

One detail that matters: mark the solved box visually (we give it a coloured border), so people can see which number was calculated and which ones they typed.

Parsing numbers people actually type

People paste "£1,200", "2%" or "4x". A forgiving parser saves a lot of frustration:

const num = v => {
  const n = parseFloat(String(v ?? '')
    .replace(/[£,%\s]/g, '')
    .replace(/x$/i, ''));
  return isFinite(n) ? n : NaN;
};
Enter fullscreen mode Exit fullscreen mode

And always check for zero before dividing. A CPM worked out from zero impressions is Infinity, which looks like a bug to anyone reading it.

Going one step further: break-even

Once the basic solver worked, the most useful addition was the break-even point, because a ROAS of 3:1 means nothing until you know your margin. The maths is simple:

const breakEvenRoas = 1 / margin;          // 25% margin -> 4:1
const maxCpa = valuePerSale * margin;      // most you can pay per sale
const maxCpc = maxCpa * conversionRate;    // most you can pay per click
Enter fullscreen mode Exit fullscreen mode

For businesses that get phone calls instead of online orders, "value per sale" becomes job value times the share of enquiries that turn into jobs. That one change makes the same calculator useful for a plumber as well as an online shop.

If the numbers show a loss, the calculator works backwards and says what would have to change to break even: a lower cost per click, a higher conversion rate, or a higher value per sale. Each of those is just the break-even equation solved for a different variable, the same trick as the "fill any two" boxes.

Shareable results without a database

We didn't want to store anything. Instead, the "copy link" button writes the inputs into the URL:

const p = new URLSearchParams();
KEYS.forEach(k => { const x = num(field(k).value); if (x > 0) p.set(k, x); });
navigator.clipboard.writeText(`${location.origin}${location.pathname}?${p}`);
Enter fullscreen mode Exit fullscreen mode

On page load we read them back from location.search. The result is a link someone can send to a colleague or client, and nothing ever leaves the browser.

Try it

The finished version is live as a free ROAS calculator, with matching CPM, CTR and CPC versions linked from it. View the page source if you want the full script. It is one small file with no dependencies.

If you build something similar, the main lesson is that the "two most recent edits" rule is what makes it feel natural. Everything else is rearranging one equation.

Top comments (0)