Creating choropleth maps often involves the need for a custom function that can map dataset values to corresponding colors. For instance, if the data ranges logarithmically from 1 to 10,000, a function like this might be necessary:
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];
}
On the other hand, when generating legend text automatically, the reverse function is required:
function index_to_val(index) {
return Math.pow(10, index);
}
var legend_labels = [0,1,2,3,4].map(index_to_val);
For simple log/exponent scenarios, writing both functions isn't too difficult. However, with more complex situations, it can become tedious. Take this 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 used to invert functions by interchanging x and y variables and solving for y. This method was only applicable to certain functions. Is there an equivalent operation in computer science?