In my application, I would like to display the state of various chemical elements depending on a given value. There is a JSON file that contains all the information about the element
{
"1":{
"Symbol":"H",
"MeltingPoint": 13.81,
"BoilingPoint": 20.28,
...
}
}
For example, there will be an input field where the user can enter a desired temperature and then will get a display of the elements, colored by their actual state. For this, I need to loop through the JSON file and then compare the values to the entered value. After the comparison, the value will be set to a corresponding position in an array and sent to an electronic display unit.
For other properties than temperature (eg. density) a very similar function will be used
The JSON-File is not changeable because it’s generated externally.
Currently, I implemented this function:
const assumedInputTemperature = 20.0;
const display = new Array(119);
const color_solid = 1;
const color_liquid = 2;
const color_gas = 3;
const color_undefinded = 4;
for (const key in elements){
const value = elements[key];
const meltingPoint = value.MeltingPoint;
const boilingPoint = value.BoilingPoint1;
const number = parseInt(key)
console.log(`${number}: ${meltingPoint} : ${boilingPoint}`)
if(meltingPoint == "" && boilingPoint == ""){
console.log("Unknown!!?")
display[number] = color_undefinded;
} else {
if (meltingPoint > assumedInputTemperature) {
display[number] = color_solid;
} else if (meltingPoint < assumedInputTemperature && boilingPoint > assumedInputTemperature) {
display[number] = color_liquid;
} else if (meltingPoint < assumedInputTemperature && boilingPoint < assumedInputTemperature) {
display[number] = color_gas;
} else {
console.log("ERROR!");
}
}
console.log(display[number]);
}
This is functional, but I wonder if there is a better approach to doing this. Are there any
recommendations for a better implementation?
2
Answers
You could use Map data structures with one of the temperature values as the key, then look up the items by key.
My suggestion falls under the heading "spend setup time and memory organizing your data structure for fast access".
But you can probably assume that there are less than 150 elements in the periodic table for the lifetime of your code (118 elements are known now). So the look-at-each-item search you have now is perfectly adequate. It’s not worth incurring complexity or test time to search that particular data set faster.
BUT, if your app is intended to search, I dunno, many organic-synthesis precursor compounds, what you have is not adequate. In the case where your dataset scales way up you should consider using a database. Many scientific apps use the simple and free SQLite database.
Don’t know exactly you want to achieve by doing it better. Your code is readable and easy understand which is good enough.
But here is example how I would do it: