brackets.js 849 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. function last(array) {
  2. return array[array.length - 1]
  3. }
  4. let brackets = {
  5. /**
  6. * Parse string to nodes tree
  7. */
  8. parse(str) {
  9. let current = ['']
  10. let stack = [current]
  11. for (let sym of str) {
  12. if (sym === '(') {
  13. current = ['']
  14. last(stack).push(current)
  15. stack.push(current)
  16. continue
  17. }
  18. if (sym === ')') {
  19. stack.pop()
  20. current = last(stack)
  21. current.push('')
  22. continue
  23. }
  24. current[current.length - 1] += sym
  25. }
  26. return stack[0]
  27. },
  28. /**
  29. * Generate output string by nodes tree
  30. */
  31. stringify(ast) {
  32. let result = ''
  33. for (let i of ast) {
  34. if (typeof i === 'object') {
  35. result += `(${brackets.stringify(i)})`
  36. continue
  37. }
  38. result += i
  39. }
  40. return result
  41. }
  42. }
  43. module.exports = brackets