Skip to content

Commit

Permalink
feat: add getAtomsFromMF
Browse files Browse the repository at this point in the history
  • Loading branch information
lpatiny committed May 13, 2021
1 parent 48c30e9 commit e29bcbf
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 5 deletions.
5 changes: 3 additions & 2 deletions src/component/elements/MolecularFormulaInput.jsx
@@ -1,8 +1,9 @@
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
import { MF } from 'mf-parser';
import { useCallback, useState } from 'react';

import getAtomsFromMF from '../../data/utilities/getAtomsFromMF';

const inputStyle = css`
text-align: center;
Expand Down Expand Up @@ -38,7 +39,7 @@ function MolecularFormulaInput({ onSave, previousMF }) {

const checkMF = useCallback((mf) => {
try {
new MF(mf);
getAtomsFromMF(mf);
return true;
} catch (error) {
return false;
Expand Down
5 changes: 2 additions & 3 deletions src/data/molecules/Molecule.js
@@ -1,7 +1,7 @@
import { MF } from 'mf-parser';
import { Molecule as OCLMolecule } from 'openchemlib/full';

import generateID from '../utilities/generateID';
import getAtomsFromMF from '../utilities/getAtomsFromMF';

/**
* @param {object} [options={}]
Expand All @@ -19,8 +19,7 @@ export function initMolecule(options = {}) {
molecule.mw = mfInfo.relativeWeight;
molecule.svg = mol.toSVG(50, 50);

const mf = new MF(molecule.mf);
molecule.atoms = mf.getInfo().atoms;
molecule.atoms = getAtomsFromMF(molecule.mf);
return molecule;
}

Expand Down
13 changes: 13 additions & 0 deletions src/data/utilities/__tests__/getAtomsFromMF.test.js
@@ -0,0 +1,13 @@
import getAtomsFromMF from '../getAtomsFromMF';

describe('getAtomsFromMF', () => {
it('correct mf', () => {
const atoms = getAtomsFromMF('C10 H20 Cl O3 Br2 C3 Cl3');
expect(atoms).toStrictEqual({ C: 13, H: 20, Cl: 4, O: 3, Br: 2 });
});
it('wrong mf', () => {
expect(() => {
getAtomsFromMF('ab C10 H20 Cl O3 Br2 C3 Cl3');
}).toThrow('MF can not be parsed: ab C10 H20 Cl O3 Br2 C3 Cl3');
});
});
23 changes: 23 additions & 0 deletions src/data/utilities/getAtomsFromMF.js
@@ -0,0 +1,23 @@
const mfCheck = /^(?:[A-Z][a-z]?\d* *)+$/;

export default function getAtomsFromMF(mf) {
if (!mfCheck.test(mf)) {
throw Error(`MF can not be parsed: ${mf}`);
}
const atoms = {};
const parts = mf.matchAll(/(?<atom>[A-Z][a-z]?)(?<number>[0-9]*)/g);
for (const part of parts) {
let { atom, number } = part.groups;
if (number === '') {
number = 1;
} else {
number = Number(number);
}
if (!atoms[atom]) {
atoms[atom] = 0;
}
atoms[atom] += number;
}

return atoms;
}

0 comments on commit e29bcbf

Please sign in to comment.