MediaWiki:CalculateMass.js
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Press Ctrl-F5.
addOnloadHook(calculateMassInit); var EXT_MASS = { "C": 12.0, "H": 1.007825035, "O": 15.99491463, "N": 14.003074002, "S": 31.97207070, "P": 30.9737620, "Na": 22.9897677, "K": 38.9637074, "Ca": 39.9625906 } var AVE_MASS = { "C": 12.0107, "H": 1.00794, "O": 15.9994, "N": 14.00674, "S": 32.066, "P": 30.973761, "Na": 22.98977, "K": 39.0983, "Ca": 40.078, } function calculateMassInit() { document.getElementById("{{{1}}}").onclick = function(){ var mass = calculateMassFromFormula(document.getElementById("{{{2}}}").value, false); document.getElementById("{{{3}}}").value = mass; } } function calculateMassFromFormula(formula, isAve) { var items = splitFormula(formula); var total = 0; var masses; if(isAve) masses = AVE_MASS; else masses = EXT_MASS; for(var i = 0; i < items.length; i += 2){ if(isFinite(masses[items[i]])) total += masses[items[i]] * items[i+1]; //console.log(masses[items[i]], items[i+1]); } //console.log(items) //console.log(total) return total; } function splitFormula(formula) { if(formula.length == 0) // 組成式が無い return []; var items = []; formula += "$"; // 番兵 var ch = formula.substr(0, 1); if(ch.match(/^[^A-Z]$/)) // フォーマットがおかしい return []; var num = 1; for(var i = 1; i < formula.length; i ++){ var next = formula.substr(i, 1); if(next.match(/^[0-9]$/)){ // 数字が終わるまでを検索する for(var j = i+1; j < formula.length; j ++){ if(formula.substr(j,1).match(/^[^0-9]$/)){ // 終了 num = parseInt(formula.substr(i,j-i), 10); i = j-1; break; } } } else if(next.match(/^[a-z]$/)){ ch += next; } else if(next.match(/^[A-Z]$/)){ items.push(ch); items.push(num); ch = next; num = 1; } else if(next == "$"){ items.push(ch); items.push(num); break; } else { // unknown return []; } } return items; }