UNPKG

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