-
Notifications
You must be signed in to change notification settings - Fork 24
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
41 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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'); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; | ||
} |