Molecular-weightJS

My web application for the chemistry department is really focused on delivering an enjoyable user experience to the researcher, rather than the usual barely functional, ugly as hell software that we get to use.

With this in mind I wanted the app to calculate the molecular weight of a compound for the user, I think it would be a nice thing to see after you just enter the chemical formula, the app just does a bit of magic and does the sum for you.

Better yet — here it is, running live in the page itself. The calculator below uses the exact atomic-mass table and mW algorithm from this post, now hydrated as a React island (try caffeine, C8H10N4O2):

194.1932g/mol
C8 → 96.088 · H10 → 10.079 · N4 → 56.027 · O2 → 31.999

Due to the app being javascript all the way through the stack, the code for calculating molecular weight based on a given properly formated chemical formula string looks like so:

mass = {
  "H":	1.00794,
  "He":	4.002602,
  "C":	12.011,
  "N":	14.00674,
  "O":	15.9994,
  // ... full periodic table ...
  "Mt":	266,
};

var mW = function (chem) {
	var s = chem.match(/([A-Z][a-z]?)(\d*)/g, chem);
	var compoundWeight = 0;
	for (var i = 0; i < s.length; i++) {
		var element = s[i].match(/([A-Z][a-z]?)/g);
		var count = s[i].match(/([0-9]*)\d/g) || 1;
		compoundWeight += mass[element] * count;
		}
	return compoundWeight
};

It first creates an object of all the atomic masses. The mW function splits up each element and quanity into different strings in an array. Then a loop iterates over each string which extracts the letters to do the look up in the atomic mass object and then it looks for the number to do the multiplication, finally the compundWeight variable is incremented.

You can find the repo on Github if you would like to contribute any changes or improvements.

I like doing code for chemistry and biology. Lets do more!

-B