Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function parseMolecule(formula) {
- // do your science here
- let result = [];
- while ((formula = parseNextChar(formula)) != '');
- function parseNextChar(str) {
- const elem = /^[A-Z]{1}[a-z]?/;
- const open = /^[({[]/;
- const close = /^[)}\]]/;
- const digit = /^[0-9]+/;
- let match;
- if (match = str.match(elem)) { // element - add object on stack
- const obj = {};
- Object.defineProperty(obj, match[0], {
- value: 1,
- enumerable: true,
- writable: true
- });
- result.push(obj);
- }
- else if (match = str.match(open)) { // opening brace - add '(' to stack
- result.push('(');
- }
- else if (match = str.match(close)) { // closing brace - merge objects backwards
- const bracketStart = result.lastIndexOf('('); // to the opening brace
- const toMerge = result.slice(bracketStart + 1);
- const mergedObj = reduceChunk(toMerge);
- result.splice(bracketStart, result.length, mergedObj);
- }
- else if (match = str.match(digit)) { // digit - multiply last object
- const multed = multObject(result[result.length - 1], match[0]);
- result.splice(result.length - 1, 1, multed);
- }
- return str = str.substr(match[0].length);
- }
- function mergeObjects(obj1, obj2) { // helpler - merge 2 objects adding missing keys
- Object.keys(obj1).forEach(key => { // and summing values of matching keys
- if (obj2.hasOwnProperty(key)) {
- obj2[key] += obj1[key];
- }
- else {
- Object.defineProperty(obj2, key, {
- value: obj1[key],
- enumerable: true,
- writable: true
- });
- }
- });
- return obj2;
- }
- function multObject(obj, mult) { // helper - multiply values
- Object.keys(obj).forEach(key => { // of all the keys of object
- obj[key] *= mult;
- });
- return obj;
- }
- function reduceChunk(array) { // helper - merge all objects of array
- return array.reduce(mergeObjects);
- }
- return reduceChunk(result);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement