applyOperation function

void applyOperation(
  1. String operator,
  2. List<double> values
)

Applies the given operator to the top two values in the values stack.

This function removes the two topmost values from the values list using the removeLast method. It then performs the arithmetic operation based on the input operator using a switch statement. If the operator is '+' or '-', the function performs addition or subtraction using the Decimal class. If the operator is '*' or '×', the function performs multiplication using the Decimal class. If the operator is '/' or '÷', the function performs division using the Decimal class and rounds the result to 32 decimal places. If the second value is zero, the function throws an exception. Finally, the function adds the result of the operation back to the values list using the add method.

Implementation

void applyOperation(String operator, List<double> values) {
  // Remove the top two values from the values stack.
  final double b = values.removeLast();
  final double a = values.removeLast();
  double result;

  // Perform the operation based on the operator.
  switch (operator) {
    case '+':
      result = a + b;
    case '-':
      result = a - b;
    case '*':
    case '×':
      result = a * b;
    case '/':
    case '÷':
      if (b == 0) throw Exception('Division by zero');
      result = a / b;
    default:
      throw Exception('Invalid operator: $operator');
  }

  // Add the result back to the values stack.
  values.add(result);
}