3

I am really struck with a question .

convert the below expression using javaScript

[ "AND", ["<", "var1", "var2"], [ "OR", [">", "var3", "var4"], ["==", "var5", "var6"] ]

to

var1 < val2 AND (var3 > val4 OR val5 == val6)

Sorry that, I dont have any more informations

Sulu.MeanStack
  • 299
  • 2
  • 3
  • 18

5 Answers5

2

try this recursive approach

var convert = function(arr) {
    if (typeof arr[0] == 'string' && arr[1] instanceof Array && arr[2] instanceof Array) {
        return ' (' + convert(arr[1]) + arr[0] + convert(arr[2]) + ') ';
    } else {
        return ' ' + arr[1] + ' ' + arr[0] + ' ' + arr[2] + ' ';
    }
}
Nishant Desai
  • 1,492
  • 3
  • 12
  • 19
0

Try this..

function rpn( input ) {
   var ar = input.split( /\s+/ ), st = [], token;
   while( token = ar.shift() ) { 
     if ( token == +token ) {
        st.push( token );
     } else {
        var n2 = st.pop(), n1 = st.pop();
        var re = /^[\+\-\/\*\>\<\==\.]$/;
        if( n1 != +n1 || n2 != +n2 || !re.test( token ) ) {
            throw new Error( 'Invalid expression: ' + input );
        }
        st.push( eval( n1 + token + ' ' + n2 ) );
     }
   }
   if( st.length !== 1 ) {
      throw new Error( 'Invalid expression: ' + input );
   }
   return st.pop();
}
sanil sathyan
  • 58
  • 1
  • 2
  • 8
0

You can try below Syntax:

if ((var1 < var2) AND (var3 > var4 OR var5==var6))
0

Try with this below mentioned Algorithm

  1. Accept a prefix string from the user.

  2. Start scanning the string from right one character at a time.

  3. If it is an operand, push it in stack.

  4. If it is an operator, pop opnd1, opnd2 and concatenate them in the order (opnd1, optr, opnd2).

  5. Push the result in the stack.

  6. Repeat these steps until arr of input prefix string ends.

  7. Pop the remaining element of the stack, which is the required Infix notation equivalent to a given Prefix notation.

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
Vishnu S Babu
  • 1,570
  • 1
  • 12
  • 23
0
Here is the simple example I did

// ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6


// If operator pop two numbers
// If number add it into stack

// 4 -> Add to stack
// 13 -> Add to stack
// 5 -> Add to stack
// / -> 13 -> a and 5 -> b (13 / 5) -> add to stack
// + -> 4 + (13 / 5)


const reverseTo = ["4", "13", "5", "/", "+"];

var stack = [];

var operators = ["+", "-", "/" , "*"];

function operation(a,b, operator){
  
  switch(operator){
    case '+':
      return a+b;
    case '/':
      return a/b;
    case '*':
      return a*b;
     case '-':
      return a-b;
  }
}


reverseTo.map(item => {
  
  if(operators.includes(item)){
       
    b = stack.pop();
    a = stack.pop();
    
    var output = operation(parseInt(a),parseInt(b),item);
//     console.log(b,a,output, item)
    stack.push(output);
    
   }else{
     stack.push(item);
   }
});

console.log(stack);
Usama Shahid
  • 769
  • 6
  • 9