quds_formula_parser 0.0.7

SDKdartflutter
Platformandroidioswindowslinuxmacosweb

Dart package designed for parsing and evaluating mathematical, logical, and textual formulas. It enables developers to input complex expressions.

Quds Formula Parser

License Pub Version

Quds Formula Parser is a powerful Dart package designed to parse, evaluate, and manipulate mathematical formulas in various forms. It supports diverse data types, including numbers, dates, and custom objects, offering a flexible solution for formula-based calculations.

Features

  • Formula Parsing: Convert mathematical expressions from infix to postfix notation.

  • Customizable Terms: Define custom functions, operators, and variables.

  • Data Types Support: Handle complex data types such as numbers, dates, durations, and logical expressions.

  • Extensible: Easily extend the library to support custom terms, types, and functions.

Supported Types

CategoryTypeDescription
NumbersReal NumbersRepresented by num and other numerical utilities.
Complex NumbersHandling of complex numbers through the ComplexNumber class.
Boolean/LogicBoolean values are managed through BooleanWrapper and related logic types.
Date and TimeDateManaged by the Date class for handling date-related functionalities.
TimeHandled by the Time class for time manipulations.
DurationRepresented by the QudsDuration class for handling time spans.
DateTimeQudsDateTime class adds specific custom handling for datetime operations.
Math and Geometry2D PointHandled by the Point2D class, which represents a point in a two-dimensional space.
3D PointHandled by the Point3D class for three-dimensional geometry.
StringsStringsManaged by StringWrapper and Strings classes for string manipulation.
IterablesIterableRepresents a collection of elements that can be iterated over, such as lists or sets.
ScienceAtomScientific data types related to chemistry and atomic structure represented by the Atom class.

Operators (Defined in the Package):

CategoryOperatorDescription
Arithmetic+Addition operator for numerical values or strings.
-Subtraction operator for numerical values.
*Multiplication operator for numerical values.
/Division operator for numerical values.
%Modulus operator to find the remainder of division.
^Exponentiation operator for raising numbers to a power.
Comparison==Equality operator to compare two values.
!=Inequality operator to check if two values are different.
>Greater than operator for numerical comparison.
<Less than operator for numerical comparison.
>=Greater than or equal to operator for numerical comparison.
<=Less than or equal to operator for numerical comparison.

Functions (Defined in the Package):

CategorySupported Functions
Mathematical FunctionsAbs, Int, Floor, Ceiling, SqRt, Square, Exp, Pow, Mod, GCD, LCM, Factorial, Fibonacci, IsPrime, IsEven, IsOdd, Clamp
Trigonometric FunctionsSin, Cos, Tan, Cot, Sec, Csc, ASin, ACos, ATan, ATan2
Logical FunctionsIf, And, Or, Not, XOR, IfError, RandomBool, AllTrue, AnyTrue, AllFalse, AnyFalse
String FunctionsLen, Lower, Upper, Trim, TrimLeft, TrimRight, Replace, Contains, StartsWith, EndsWith, Concat, ToStr
Date & Time FunctionsDate, Year, Month, Day, WeekDay, Days, Now, Today, Hour, Minute, Second
Geometry FunctionsPoint, Point.X, Point.Y, Point.Z, Distance, Hypotenuse
Statistical FunctionsAvg, Product, Count, Max, Min, Median, Sum, Variance, StDev, Mode, Permutations, Combinations
Iterable FunctionsList, Reverse
Set OperationsSet, Union, Intersect, Difference
Atom FunctionsAtom, Atom.Name, Atom.Symbol, Atom.Number, Atom.Weight, Atom.BoilingPoint, Atom.MeltingPoint, Atom.Density, Atom.IonizationEnergy, Atom.Row, Atom.Column, Atom.EarthCrust, Atom.DiscoveryYear, Atom.GroupNumber
Core FunctionsType, ValueType, IsNumber, IsReal, IsComplex, IsPoint, IsPoint2D, IsPoint3D, IsDate, IsTime, IsDateTime, IsDuration, IsBool, IsFraction, IsAtom, IsText

Installation

Add the following to your pubspec.yaml file:


dependencies:

quds_formula_parser: ^1.0.0

Then, run:


flutter  pub  get

Usage

Basic Usage

Here's an example of parsing and evaluating a simple formula:

import 'package:quds_formula_parser/quds_formula_parser.dart';

dynamic _parseFormulaAndEvaluate(String str) {
  FormulaParser parser = FormulaParser();

  var formula = parser.parse(str);

  var supporter = FormulaInfixToPostfixConvertor(formula: formula);

  var result = supporter.evaluate();

  if (result is ValueWrapper) return result.value;

  return result;
}

void main() {
  _evaluateSimpleFormulas();
}

Supporting and setting variable values

You can also define custom variable and use it with custom value in your formulas:

import 'package:quds_formula_parser/quds_formula_parser.dart';

void _evaluatingWithVariables() {
  var provider = FormulaProvider.defaultInstance;

  FormulaParser parser = FormulaParser(provider: provider);

  provider.insertVariable(Variable(symbol: 'x', value: 0));

  String formulaStr = 'power(x,2)';

  var formula = parser.parse(formulaStr);

  var supporter = FormulaInfixToPostfixConvertor(formula: formula);

  Stopwatch stopwatch = Stopwatch();

  stopwatch.start();

  int times = 1000000;

  for (int i = 0; i < times; i++) {
    provider.setVariableValue('x', i);

    supporter.evaluate();
  }

  stopwatch.stop();

  print(
      '$formulaStr evaluating times($times) took ${stopwatch.elapsedMilliseconds} ms');
}

void main() {
  _evaluatingWithVariables();
}

Defining custom function with using it

You can also define custom function and use it in your formulas:

import 'package:quds_formula_parser/quds_formula_parser.dart';

void _parseAndEvaluateWithCustomProvider() {
// Prepare the terms provider

  FormulaProvider provider = FormulaProvider();

  provider.identifiers.addAll([
    BracketIdentifier(),
    NamedValuesIdentifier(provider: provider),
    FunctionIdentifier(functions: [_CustomFunction()])
  ]);

// Prepare the parser

  var parser = FormulaParser(provider: provider);

  provider.insertVariable(Variable(symbol: 'x', value: 0));

  var formula = parser.parse('randomize(x)');

  var supporter = FormulaInfixToPostfixConvertor(formula: formula);

  for (int i = 0; i < 10; i++) {
    provider.setVariableValue('x', i);

    print(supporter.evaluate());
  }
}

void main() {
  _parseAndEvaluateWithCustomProvider();
}

Example

See the example directory for a full example on how to use the package.

Contributions

Contributions are welcome! Feel free to submit pull requests or open issues on our GitHub page.

License

This package is licensed under the MIT License. See the LICENSE file for more information.