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