Program to evaluate simple expressions | A utility function to check if a given character is operand ; utility function to find value of and operand ; This function evaluates simple expressions . It returns - 1 if the given expression is invalid . ; Base Case : Given expression is empty ; The first character must be an operand , find its value ; Traverse the remaining characters in pairs ; The next character must be an operator , and next to next an operand ; If next to next character is not an operand ; Update result according to the operator ; If not a valid operator ; Driver program to test above function
function isOperand ( c ) { return ( c . charCodeAt ( 0 ) >= ' ' . charCodeAt ( 0 ) && c . charCodeAt ( 0 ) <= ' ' . charCodeAt ( 0 ) ) ; } function value ( c ) { return ( c . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ; } function evaluate ( exp ) { if ( exp . length == 0 ) return - 1 ; let res = value ( exp [ 0 ] ) ; for ( let i = 1 ; i < exp . length ; i += 2 ) { let opr = exp [ i ] , opd = exp [ i + 1 ] ; if ( isOperand ( opd ) == false ) return - 1 ; if ( opr == ' ' ) res += value ( opd ) ; else if ( opr == ' ' ) res -= value ( opd ) ; else if ( opr == ' ' ) res *= value ( opd ) ; else if ( opr == ' ' ) res /= value ( opd ) ; else return - 1 ; } return res ; } let expr1 = " " ; let res = evaluate ( expr1 ) ; if ( res == - 1 ) document . write ( expr1 + " " ) ; else document . write ( " " + expr1 + " " + res + " " ) ; let expr2 = " " ; res = evaluate ( expr2 ) ; if ( res == - 1 ) document . write ( expr2 + " " ) ; else document . write ( " " + expr2 + " " + res + " " ) ; let expr3 = " " ; res = evaluate ( expr3 ) ; if ( res == - 1 ) document . write ( expr3 + " " ) ; else document . write ( " " + expr3 + " " + res + " " ) ; let expr4 = " " ; res = evaluate ( expr4 ) ; if ( res == - 1 ) document . write ( expr4 + " " ) ; else document . write ( " " + expr4 + " " + res + " " ) ;