Advertisement
Guest User

Untitled

a guest
Jul 18th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. function parseMolecule(formula) {
  2. // do your science here
  3. let result = [];
  4. while ((formula = parseNextChar(formula)) != '');
  5. function parseNextChar(str) {
  6. const elem = /^[A-Z]{1}[a-z]?/;
  7. const open = /^[({[]/;
  8. const close = /^[)}\]]/;
  9. const digit = /^[0-9]+/;
  10. let match;
  11. if (match = str.match(elem)) { // element - add object on stack
  12. const obj = {};
  13. Object.defineProperty(obj, match[0], {
  14. value: 1,
  15. enumerable: true,
  16. writable: true
  17. });
  18. result.push(obj);
  19. }
  20. else if (match = str.match(open)) { // opening brace - add '(' to stack
  21. result.push('(');
  22. }
  23. else if (match = str.match(close)) { // closing brace - merge objects backwards
  24. const bracketStart = result.lastIndexOf('('); // to the opening brace
  25. const toMerge = result.slice(bracketStart + 1);
  26. const mergedObj = reduceChunk(toMerge);
  27. result.splice(bracketStart, result.length, mergedObj);
  28. }
  29. else if (match = str.match(digit)) { // digit - multiply last object
  30. const multed = multObject(result[result.length - 1], match[0]);
  31. result.splice(result.length - 1, 1, multed);
  32. }
  33. return str = str.substr(match[0].length);
  34. }
  35. function mergeObjects(obj1, obj2) { // helpler - merge 2 objects adding missing keys
  36. Object.keys(obj1).forEach(key => { // and summing values of matching keys
  37. if (obj2.hasOwnProperty(key)) {
  38. obj2[key] += obj1[key];
  39. }
  40. else {
  41. Object.defineProperty(obj2, key, {
  42. value: obj1[key],
  43. enumerable: true,
  44. writable: true
  45. });
  46. }
  47. });
  48. return obj2;
  49. }
  50. function multObject(obj, mult) { // helper - multiply values
  51. Object.keys(obj).forEach(key => { // of all the keys of object
  52. obj[key] *= mult;
  53. });
  54. return obj;
  55. }
  56. function reduceChunk(array) { // helper - merge all objects of array
  57. return array.reduce(mergeObjects);
  58. }
  59. return reduceChunk(result);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement