Reversible functions in Javascript

409 Views Asked by At

I make a lot of choropleth maps for which I need a custom function that accepts values from the dataset and returns the corresponding colors. For example, data that is distributed logarithmically from 1 to 10,000 might require this function:

var colors = ["#ffffcc","#c2e699","#78c679","#31a354","#006837"];
function val_to_index(val) {
    var index = Math.floor(Math.log(val) / Math.log(10));
    return colors[index];
}

When automatically building out the text for the legend, meanwhile, I need the reverse function:

function index_to_val(index) {
    return Math.pow(10, index);
}
var legend_labels = [0,1,2,3,4].map(index_to_val);

When it's something as simple as a log/exponent, it's no trouble to write both functions. But when it's more complex, it gets really tedious. For example:

    // divisions of 50,100,500,1000,5000,etc
function val_to_index(v) {
    var lg = Math.log(v) / Math.log(10);
    var remainder = lg % 1 > (Math.log(5) / Math.log(10)) ? 1 : 0;
    var index = return Math.floor(lg) * 2 - 3 + remainder;
    return colors[index];
}

function index_to_val(index) {
    index += 3;
    return Math.pow(10, Math.floor(index/2)) * Math.pow(5, index%2);
}

In middle school algebra, we learned to invert functions automatically by reversing the x and y variables and solving for y (which, of course, was only possible for certain functions). My question is this: Is there an equivalent operation in computer science?

1

There are 1 best solutions below

0
On

Automatically finding a function's inverse would require a computer algebra solver (CAS) library of some sort. If you always do the forward operation, first, though, there may be a simpler way; instead of discarding the original data, wrap the original value and the result of the computation together in an object. This way, computing the inverse merely requires retrieving the field containing the original value.