fork download
  1. init(NaCl, 4)
  2. function init(formula, dec) {
  3. //set precision
  4.  
  5. //start the actual work :)
  6. formulaComponents = splitFormula(formula);
  7. parse(formulaComponents);
  8. display();
  9. }
  10.  
  11.  
  12. //if formula = C6H2(NO2)3CH3, then the array returned contains: C6, H2, (NO2)3, CH3
  13. function splitFormula(formula) {
  14. re = /([A-Z][a-z]?[0-9]*)|(\(.*?\)\d*)/g;
  15. return formula.match(re);
  16. }
  17.  
  18.  
  19. function parse(formulaComponents) {
  20. total = 0; //total weight
  21.  
  22. //traverse the components
  23. for (var i = 0; i < formulaComponents.length; i++) {
  24. //handle every component, one by one
  25. var weightOfi = manageBrackets(formulaComponents[i]);
  26. total += weightOfi;
  27. }
  28.  
  29. //when everythings processed..
  30.  
  31. //add subscript to numbers in the formula
  32. var formula_formatted = formula.replace(/\d/g, "<sub>$&</sub>");
  33. alert(total.toFixed(dec))
  34. }
  35.  
  36.  
  37. function manageBrackets(comp) {
  38. //is the given component bracket enclosed?
  39. if (comp.indexOf("(") != -1) {
  40.  
  41. //yes, split it to:
  42.  
  43. //1) what's inside the bracket
  44. var insideBracket = comp.match(/\(([^)]*)\)/g)[0];
  45. insideBracket = insideBracket.substring(1, insideBracket.length-1);
  46.  
  47. //2)how many times to multiply
  48. var num = comp.match(/[0-9]*$/mg)[0];
  49. var num = (num != "") ? num : 1;
  50.  
  51.  
  52. //more complexity inside the bracket, split it again
  53. var form = splitFormula(insideBracket);
  54.  
  55. //local total to hold the weight of the expr inside bracket
  56. var total = 0;
  57. for (var i = 0; i < form.length; i++) {
  58. total += simpleExpr(form[i]);//fromComplex means it's a part inside the brackets (to handle printing)
  59. }
  60.  
  61.  
  62.  
  63. total *= num;
  64.  
  65.  
  66.  
  67. return total;
  68.  
  69. } else {
  70. //if it's a simple expr, process it directly
  71. return simpleExpr(comp);
  72. }
  73. }
  74.  
  75.  
  76. function simpleExpr(comp) {
  77. //get elem name and num
  78. var elem = comp.match(/[A-Z][a-z]?/g);
  79. var num = comp.match(/[0-9]+/g);
  80. var num = (num != null) ? num : 1;
  81.  
  82. var weight = calcWeight(elem, num);
  83.  
  84. return weight;
  85. }
  86.  
  87. function calcWeight(elem, num) {
  88. return (atom[elem] * num);
  89. }
  90.  
Runtime error #stdin #stdout 0.31s 214272KB
stdin
Standard input is empty
stdout
Standard output is empty