
/*
PROBLEM: Evaluate a Nested Math Expression
FOLLOW-UP 2: Variable Number of Arguments

Functions:
add(x1, x2, ..., xk)
sub(x1, x2, ..., xk)
mul(x1, x2, ..., xk)
div(x1, x2, ..., xk)
pow(x1, x2, ..., xk)

Examples:
add(1,2,3,4)             -> 10
mul(2,3,4)               -> 24
sub(20,5,3)              -> 12
div(100,2,5)             -> 10
pow(2,3,2)               -> 64
add(1,mul(2,3,4),5)      -> 30

ASSUMPTIONS:
- Input is valid.
- Every function has at least one argument.
- add/mul combine all arguments.
- sub/div/pow are evaluated left to right.
- Unary operations return their only argument.
- Division truncates toward zero after each step.
- Exponents are nonnegative integers.
- Intermediate results fit signed 32-bit integers.

APPROACH: TWO STACKS

names:
  Stores frames containing:
  { operation, startIndex }
  Here startIndex reprsents elements in the values arr.
values:
  Stores integers and completed subexpression results.

When a function starts:
  Save values.length as startIndex.

When ')' is encountered:
  All values from startIndex onward are arguments
  belonging to that function.

  Evaluate them from left to right.
  Replace them with one result.

TIME: O(n), under fixed-width arithmetic assumptions.
SPACE: O(d), where d is maximum nesting depth,
       plus pending arguments; worst case O(n).
*/

function evaluateExpression(s) {
    const names = [];
    const values = [];

    let i = 0;

    function skipSpaces() {
        while (i < s.length && s[i] === ' ') {
            i++;
        }
    }

    function isNumberStart(ch) {
        return ch === '-' || (ch >= '0' && ch <= '9');
    }

    function parseNumber() {
        const start = i;

        if (s[i] === '-') i++;

        while (
            i < s.length &&
            s[i] >= '0' &&
            s[i] <= '9'
        ) {
            i++;
        }

        return Number(s.slice(start, i));
    }

    function parseOperation() {
        const operation = s.slice(i, i + 3);
        i += 3;
        return operation;
    }

    // Apply one operation to two values.
    function applyCall(operation, x, y) {
        if (operation === 'add') return x + y;
        if (operation === 'sub') return x - y;
        if (operation === 'mul') return x * y;
        if (operation === 'div') return Math.trunc(x / y);
        if (operation === 'pow') return Math.pow(x, y);
    }

    // Evaluate all arguments in their original order.
    function evaluateArgs(operation, args) {
        let result = args[0];

        for (let j = 1; j < args.length; j++) {
            result = applyCall(operation, result, args[j]);
        }

        return result;
    }

    while (i < s.length) {
        skipSpaces();

        if (i >= s.length) break;

        // Case 1: Number
        if (isNumberStart(s[i])) {
            values.push(parseNumber());
        }

        // Case 2: Function name
        else if (s[i] >= 'a' && s[i] <= 'z') {
            const operation = parseOperation();

            // Remember where this function's arguments begin.
            names.push({
                operation,
                startIndex: values.length
            });
        }

        // Case 3: Completed function call
        else if (s[i] === ')') {
            const frame = names.pop();

            // Extract this function's arguments.
            // splice removes them from values.
            const args = values.splice(frame.startIndex);

            // Evaluate arguments from left to right.
            const result = evaluateArgs(
                frame.operation,
                args
            );

            // Replace all arguments with one result.
            values.push(result);

            i++;
        }

        // Case 4: Skip '(' and ','
        else {
            i++;
        }
    }

    return values[0];
}


// ---------------- TEST HARNESS ----------------

const tests = [
    ["add(1,2,3,4)", 10],
    ["mul(2,3,4)", 24],
    ["sub(20,5,3)", 12],
    ["div(100,2,5)", 10],
    ["pow(2,3,2)", 64],

    // Nested operations
    ["add(1,mul(2,3,4),5)", 30],
    ["sub(20,add(2,3),4)", 11],
    ["mul(add(1,2,3),sub(10,4,2))", 24],

    // Unary functions
    ["add(5)", 5],
    ["mul(-3)", -3],
    ["sub(10)", 10],

    // Negative division
    ["div(-20,3,2)", -3],

    // Powers
    ["pow(2,0,3)", 1],
    ["pow(0,0)", 1],

    // Standalone number
    ["42", 42],

    // Whitespace
    ["add( 1 , 2 , mul( 3 , 4 ) )", 15]
];

tests.forEach(([input, expected], index) => {
    const actual = evaluateExpression(input);

    console.log(
        `Test ${index + 1}: ` +
        (actual === expected ? "PASS" : "FAIL") +
        ` | Expected: ${expected}` +
        ` | Actual: ${actual}`
    );
});
/*
TIME COMPLEXITY: O(n)

n = total length of the expression
k = number of arguments in a particular function

1. Parsing:
   - Each character is processed once.
   - Total = O(n).

2. Extracting arguments:
   - values.splice(startIndex) extracts k arguments.
   - Cost per function = O(k).
   - Across all functions, the total number of
     argument positions is O(n).
   - Total extraction cost = O(n).

3. Evaluating arguments:
   - evaluateArgs() processes k arguments.
   - Cost per function = O(k).
   - Across all functions = O(n).

4. Arithmetic:
   - Fixed-width operations are treated as O(1).
   - Math.pow() is treated as O(1) for this problem.

OVERALL TIME = O(n).


SPACE COMPLEXITY: O(n)

d = maximum nesting depth

1. names stack:
   - Stores one frame per unfinished function.
   - O(d) space.

2. values stack:
   - Stores arguments and intermediate results.
   - A single function can have O(n) arguments.
   - O(n) space.

3. Temporary args array:
   - splice() can extract O(n) arguments.
   - O(n) temporary space.

OVERALL AUXILIARY SPACE = O(n).

IMPORTANT DIFFERENCE:

Original problem (exactly 2 arguments):
   Space = O(d)

Follow-up (variable number of arguments):
   Space = O(n)

Even when d = 1, a function such as
add(1,1,1,1,...,1) can require O(n) space.
*/
