brackets.js 1.9 KB

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