Dynamic table under calculator

Another useful addition to your calculator is a table. This is especially interesting for finance calculators since they tend to manage big amounts of data over different periods of time.

To create a table, the data needs to be arranged in a similar way to that of a chart. We will show you here how to dynamically create this data so that it will be reactive to the user’s input.

See also

We have created a calculator using this code so that you can see the results for yourself. Check it out at Dynamic Table on BB.

For our example we will use the same example equation as for the chart example: f(x) = xⁿ + offset. We will have 3 columns. The first column will be the value of x, the second will show the value of f(x) and the third will be the sum for all previous values of f(x).

 1'use strict';
 2
 3omni.onResult(['a', 'b', 'offset', 'n'], function(ctx) {
 4  var tableData = [],
 5    n = ctx.getNumberValue('n'),
 6    a = ctx.getNumberValue('a'),
 7    b = ctx.getNumberValue('b'),
 8    offset = ctx.getNumberValue('offset'),
 9    runningSum = 0,
10    header = ['x','f(x)', 'sum'];
11
12  for (var i = a; i <= b; i++) {
13    runningSum += mathjs.pow(i, n) + offset;
14    tableData.push([i, // x
15                    mathjs.pow(i, n) + offset, // f(x)
16                    runningSum // sum
17                    ]);
18  }
19  ctx.addTextInfo('Table of Values');
20  ctx.addTable(tableData, header);
21});

As you can see this is a very simple procedure once you understand how to dynamically create data in an array. Just remember that tables should have a header input as an array of strings.

Tip

The headers can be created statically (like in the example) or dynamically to adapt to user input.