init(NaCl, 4)
function init(formula, dec) {
//set precision
//start the actual work :)
formulaComponents = splitFormula(formula);
parse(formulaComponents);
display();
}
//if formula = C6H2(NO2)3CH3, then the array returned contains: C6, H2, (NO2)3, CH3
function splitFormula(formula) {
re = /([A-Z][a-z]?[0-9]*)|(\(.*?\)\d*)/g;
return formula.match(re);
}
function parse(formulaComponents) {
total = 0; //total weight
//traverse the components
for (var i = 0; i < formulaComponents.length; i++) {
//handle every component, one by one
var weightOfi = manageBrackets(formulaComponents[i]);
total += weightOfi;
}
//when everythings processed..
//add subscript to numbers in the formula
var formula_formatted = formula.replace(/\d/g, "<sub>$&</sub>");
alert(total.toFixed(dec))
}
function manageBrackets(comp) {
//is the given component bracket enclosed?
if (comp.indexOf("(") != -1) {
//yes, split it to:
//1) what's inside the bracket
var insideBracket = comp.match(/\(([^)]*)\)/g)[0];
insideBracket = insideBracket.substring(1, insideBracket.length-1);
//2)how many times to multiply
var num = comp.match(/[0-9]*$/mg)[0];
var num = (num != "") ? num : 1;
//more complexity inside the bracket, split it again
var form = splitFormula(insideBracket);
//local total to hold the weight of the expr inside bracket
var total = 0;
for (var i = 0; i < form.length; i++) {
total += simpleExpr(form[i]);//fromComplex means it's a part inside the brackets (to handle printing)
}
total *= num;
return total;
} else {
//if it's a simple expr, process it directly
return simpleExpr(comp);
}
}
function simpleExpr(comp) {
//get elem name and num
var elem = comp.match(/[A-Z][a-z]?/g);
var num = comp.match(/[0-9]+/g);
var num = (num != null) ? num : 1;
var weight = calcWeight(elem, num);
return weight;
}
function calcWeight(elem, num) {
return (atom[elem] * num);
}