A parser for chemical formula strings.
An demo of this package in action can be found here: Molar Mass Calculator
// ES6
import { tokenize, countElements, getMass } from 'oganesson';
tokenize(<formula>)
// ES5
const oganesson = require('oganesson');
oganesson.tokenize(<formula>)
Tokenizes the given formula.
-
formula (String): The chemical formula to tokenize.
Note: The formula does not necessarily have to be valid.
An object with an array of tokens.
tokenize('Ba(NO3)2');
[
{
"type": "element",
"value": "Ba"
},
{
"type": "parenthesis",
"value": "open"
},
{
"type": "element",
"value": "N"
},
{
"type": "element",
"value": "O"
},
{
"type": "subscript",
"value": 3
},
{
"type": "parenthesis",
"value": "close"
},
{
"type": "subscript",
"value": 2
}
]
tokenize('B)(')
[
{
"type": "element",
"value": "B"
},
{
"type": "parenthesis",
"value": "close"
},
{
"type": "parenthesis",
"value": "open"
}
]
tokenize('aB)(')
// Throws an error
Counts the number of each element in the given tokens.
-
tokens (Array): An array of tokens
Note: The tokens should be in the format that
tokenize
returns.
An object with each element mapped to the number of instances it occurs in the tokenization.
countElements(tokenize('Ba(NO3)2');
{
"Ba": 1,
"N": 2,
"O": 6
}
Gets the total mass of the given counts.
-
counts (Object): The counts of each element.
Note: The counts should be in the format that
countElements
returns.
The total mass of the given counts.
getMass(countElements(tokenize('Ba(NO3)2')));
261.33
- Throw an error in either
tokenize
orcountElements
when the formula is invalid.