Advertisement
IzhanVarsky

Untitled

Mar 27th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. function getFullByRegExp(reg) {
  3.     let res = "";
  4.     while (ind < expr.length && reg.test(expr[ind])) {
  5.         res += expr[ind];
  6.         ind++;
  7.     }
  8.     return res;
  9. }
  10.  
  11. function skipWhiteSpaces() {
  12.     while (ind < expr.length && /\s/.test(expr[ind])) {
  13.         ind++;
  14.     }
  15. }
  16.  
  17. function getOperation() {
  18.     skipWhiteSpaces();
  19.     switch (expr[ind]) {
  20.         case '-':
  21.         case '+':
  22.         case '/':
  23.         case '*':
  24.             return expr[ind];
  25.         default :
  26.         // ошибка
  27.     }
  28. }
  29.  
  30. function getOperand() {
  31.     let curStack = [];
  32.     skipWhiteSpaces();
  33.     switch (expr[ind]) {
  34.         case '(':
  35.             ind++;
  36.             let symb = getOperation();
  37.             curStack.push(symb);
  38.             ind++;
  39.             let op1 = getOperand();
  40.             ind++;
  41.             let op2 = getOperand();
  42.             for (let i = 0; i < op2.length; i++){
  43.                 curStack.push(op2[i]);
  44.             }
  45.             for (let i = 0; i < op1.length; i++){
  46.                 curStack.push(op1[i]);
  47.             }
  48.             break;
  49.         case ')':
  50.             ind++;
  51.             break;
  52.         default :
  53.             let st = [];
  54.             if (/[A-Za-z]/.test(expr[ind])) {
  55.                 st.push(getFullByRegExp(/[A-Za-z]/));
  56.                 return st;
  57.             } else if (/\d/.test(expr[ind])) {
  58.                 st.push(parseInt(getFullByRegExp(/\d/)));
  59.                 return st;
  60.             } else {
  61.                 // error
  62.             }
  63.     }
  64.     return curStack;
  65. }
  66.  
  67. const parsePrefix = function (str) {
  68.     ind = 0;
  69.     expr = str;
  70.     skipWhiteSpaces();
  71.     switch (expr[ind]) {
  72.         case '(':
  73.             ind++;
  74.             let symb = getOperation();
  75.             stack.push(symb);
  76.             ind++;
  77.             let op1 = getOperand();
  78.             ind++;
  79.             let op2 = getOperand();
  80.             for (let i = 0; i < op2.length; i++){
  81.                 stack.push(op2[i]);
  82.             }
  83.             for (let i = 0; i < op1.length; i++){
  84.                 stack.push(op1[i]);
  85.             }
  86.             break;
  87.     }
  88.     let res = "";
  89.     while (stack.length > 0) {
  90.         res += stack.pop();
  91.         res += " ";
  92.     }
  93.     // return parse(res);
  94.     return res;
  95. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement