FormulaParser constructor

FormulaParser(
  1. String expression, [
  2. Map<String, dynamic>? options
])

Constructs a FormulaParser instance with the given expression and options.

Implementation

FormulaParser(this.expression, [this.options]) {
  String tempExp = expression;
  options?.forEach((key, value) {
    if (availableFunctions.contains(key.toLowerCase()) &&
        tempExp.contains(key.toLowerCase())) {
      _isReservedWordsUsed = true;
      _reservedWordsUsed.add(key);
    } else {
      // ⭐ FIX: Handle different value types appropriately
      String safeValue;

      if (value == null || value.toString().isEmpty) {
        safeValue = '""';
      } else if (value is num || value == "null") {
        safeValue = value.toString(); // keep raw numbers
      } else if (value is bool) {
        safeValue =
            value.toString().toUpperCase(); // TRUE or FALSE (unquoted)
      } else if (value.toString().toLowerCase() == 'true' ||
          value.toString().toLowerCase() == 'false') {
        // ⭐ Convert string boolean to actual boolean
        safeValue =
            value.toString().toUpperCase(); // TRUE or FALSE (unquoted)
      } else {
        final clean = value.toString().replaceAll('"', '');
        safeValue = '"$clean"'; // wrap strings in quotes
      }

      // Use case-insensitive matching to handle case mismatches between
      // schema fieldNames and expression variable names
      tempExp = tempExp.replaceAll(
        RegExp(r'\b' + RegExp.escape(key) + r'\b', caseSensitive: false),
        safeValue,
      );
    }
  });

  // remove unnecessary spaces
  // & make it all uppercase to make the parsing easier
  _inputExpression = tempExp.toUpperCase().replaceAll(" ", "");
}