You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.6 KiB

4 years ago
  1. "use strict";
  2. function last(array) {
  3. return array[array.length - 1];
  4. }
  5. var brackets = {
  6. /**
  7. * Parse string to nodes tree
  8. */
  9. parse: function parse(str) {
  10. var current = [''];
  11. var stack = [current];
  12. for (var _iterator = str, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  13. var _ref;
  14. if (_isArray) {
  15. if (_i >= _iterator.length) break;
  16. _ref = _iterator[_i++];
  17. } else {
  18. _i = _iterator.next();
  19. if (_i.done) break;
  20. _ref = _i.value;
  21. }
  22. var sym = _ref;
  23. if (sym === '(') {
  24. current = [''];
  25. last(stack).push(current);
  26. stack.push(current);
  27. continue;
  28. }
  29. if (sym === ')') {
  30. stack.pop();
  31. current = last(stack);
  32. current.push('');
  33. continue;
  34. }
  35. current[current.length - 1] += sym;
  36. }
  37. return stack[0];
  38. },
  39. /**
  40. * Generate output string by nodes tree
  41. */
  42. stringify: function stringify(ast) {
  43. var result = '';
  44. for (var _iterator2 = ast, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) {
  45. var _ref2;
  46. if (_isArray2) {
  47. if (_i2 >= _iterator2.length) break;
  48. _ref2 = _iterator2[_i2++];
  49. } else {
  50. _i2 = _iterator2.next();
  51. if (_i2.done) break;
  52. _ref2 = _i2.value;
  53. }
  54. var i = _ref2;
  55. if (typeof i === 'object') {
  56. result += "(" + brackets.stringify(i) + ")";
  57. continue;
  58. }
  59. result += i;
  60. }
  61. return result;
  62. }
  63. };
  64. module.exports = brackets;