Oganesson
A parser for chemical formula strings.
API
import { tokenize, countElements, getMass } from 'oganesson';
tokenize(<formula>)
const oganesson = require('oganesson');
oganesson.tokenize(<formula>)
tokenize(formula)
Tokenizes the given formula.
Arguments
- formula (String): The chemical formula to tokenize.
Note: The formula does not necessarily have to be valid.
Returns
An object with an array of tokens.
Examples
Valid formula
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
}
]
Invalid, but parseable formula
tokenize('B)(')
[
{
"type": "element",
"value": "B"
},
{
"type": "parenthesis",
"value": "close"
},
{
"type": "parenthesis",
"value": "open"
}
]
Unparseable formula
tokenize('aB)(')
countElements(tokens)
Counts the number of each element in the given tokens.
Arguments
- tokens (Array): An array of tokens
Note: The tokens should be in the format that tokenize
returns.
Returns
An object with each element mapped to the number of instances it occurs in the tokenization.
Examples
countElements(tokenize('Ba(NO3)2');
{
"Ba": 1,
"N": 2,
"O": 6
}
getMass(counts)
Gets the total mass of the given counts.
Arguments
- counts (Object): The counts of each element.
Note: The counts should be in the format that countElements
returns.
Returns
The total mass of the given counts.
Examples
getMass(countElements(tokenize('Ba(NO3)2')));
261.33
Todo
- Throw an error in either
tokenize
or countElements
when the formula is invalid.