brackets.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }
  3. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  4. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  5. function last(array) {
  6. return array[array.length - 1];
  7. }
  8. var brackets = {
  9. /**
  10. * Parse string to nodes tree
  11. */
  12. parse: function parse(str) {
  13. var current = [''];
  14. var stack = [current];
  15. for (var _iterator = _createForOfIteratorHelperLoose(str), _step; !(_step = _iterator()).done;) {
  16. var sym = _step.value;
  17. if (sym === '(') {
  18. current = [''];
  19. last(stack).push(current);
  20. stack.push(current);
  21. continue;
  22. }
  23. if (sym === ')') {
  24. stack.pop();
  25. current = last(stack);
  26. current.push('');
  27. continue;
  28. }
  29. current[current.length - 1] += sym;
  30. }
  31. return stack[0];
  32. },
  33. /**
  34. * Generate output string by nodes tree
  35. */
  36. stringify: function stringify(ast) {
  37. var result = '';
  38. for (var _iterator2 = _createForOfIteratorHelperLoose(ast), _step2; !(_step2 = _iterator2()).done;) {
  39. var i = _step2.value;
  40. if (typeof i === 'object') {
  41. result += "(" + brackets.stringify(i) + ")";
  42. continue;
  43. }
  44. result += i;
  45. }
  46. return result;
  47. }
  48. };
  49. module.exports = brackets;