brackets.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. (function() {
  2. var brackets, last;
  3. last = function(array) {
  4. return array[array.length - 1];
  5. };
  6. brackets = {
  7. parse: function(str) {
  8. var current, j, len, stack, sym;
  9. current = [''];
  10. stack = [current];
  11. for (j = 0, len = str.length; j < len; j++) {
  12. sym = str[j];
  13. if (sym === '(') {
  14. current = [''];
  15. last(stack).push(current);
  16. stack.push(current);
  17. } else if (sym === ')') {
  18. stack.pop();
  19. current = last(stack);
  20. current.push('');
  21. } else {
  22. current[current.length - 1] += sym;
  23. }
  24. }
  25. return stack[0];
  26. },
  27. stringify: function(ast) {
  28. var i, j, len, result;
  29. result = '';
  30. for (j = 0, len = ast.length; j < len; j++) {
  31. i = ast[j];
  32. if (typeof i === 'object') {
  33. result += '(' + brackets.stringify(i) + ')';
  34. } else {
  35. result += i;
  36. }
  37. }
  38. return result;
  39. }
  40. };
  41. module.exports = brackets;
  42. }).call(this);