How can I modify my Shunting-Yard Algorithm so it accepts unary operators?

后端 未结 6 624
眼角桃花
眼角桃花 2020-12-09 16:25

I\'ve been working on implementing the Shunting-Yard Algorithm in JavaScript for class.

Here is my work so far:

var userInput = prompt(\"Enter in a m         


        
6条回答
  •  醉梦人生
    2020-12-09 16:48

    To handle floating point numbers you can change your (number part of) regex to:

    /([0-9]+\.?[0-9]*)/
    

    so the final regex would be:

    /([0-9]+\.?[0-9]*|[*+-\/()])/
    

    And for handling unary minus operator, you can change it to another character like 'u'. (As it is explained here by -TGO)

    The javascript code that i wrote for handling unary minus operator based on the link given is:

    // expr is the given infix expression from which, all the white spaces has been
    // removed.(trailing and leading and in between white space characters)
    const operators = ['+', '*', '-', '/', '^'];
    const openingBrackets = ['(', '[', '{'];
    let exprArr = Array.from(expr);
    // Since strings are immutable in js, I am converting it to an array for changing 
    // unary minus to 'u'
    for (let i = 0; i < expr.length; i++) {
        if (expr[i] === '-') {
            if (i === 0) {
                exprArr[i] = 'u';
            } else if (operators.includes(expr[i - 1])) {
                exprArr[i] = 'u';
            } else if (openingBrackets.includes(expr[i - 1])) {
                exprArr[i] = 'u';
            } else {
                // '-' is not a unary operator
                // it is a binary operator or we have the wrong expression, so...
                if (!openingBrackets.includes(expr[i + 1]) && !/[0-9]/.test(expr[i + 1])) {
                    throw new Error("Invalid Expression...");
                }
            }
        }
    }
    // And finally converting back to a string.
    let expr2 = exprArr.join('');
    

提交回复
热议问题