UNPKG

smartcal

Version:

A powerful, lightweight TypeScript library for dynamic mathematical expression evaluation with support for variables, formulas, Unicode strings, and compiled expressions for high performance.

312 lines (299 loc) 12.4 kB
// Generated by dts-bundle v0.7.3 export { ConditionResult, CompiledExpression }; /** * Represents a compiled formula expression that can be evaluated with data. * * This interface defines the contract for compiled expressions that have been pre-parsed * into an AST for efficient repeated evaluation. * * @interface */ export interface CompiledExpression { /** Type identifier for the compiled expression */ type: "CompiledExpression"; /** * Evaluates the compiled expression with the provided data. * * @template T - The type of the data object containing variables * @param {T} data - The data object to evaluate the expression against. * Should contain all variables referenced in the original expression. * @returns {string | number} The result of the evaluation, either a number or string * * @example * ```typescript * const expr = compile("price * quantity"); * expr.evaluate({ price: 10, quantity: 5 }); // 50 * ``` * * @throws {FormulaVariableNotFoundError} When required variables are missing from data */ evaluate<T extends DataType>(data: T): string | number; /** * Returns the string representation of the original expression. * * @returns {string} The original expression string that was compiled * * @example * ```typescript * const expr = compile("x + y * 2"); * console.log(expr.toString()); // "x + y * 2" * ``` */ toString(): string; } /** * Implementation of the CompiledExpression interface for formula expressions. * * This class provides a concrete implementation that compiles a formula expression * once and allows efficient repeated evaluation with different data sets. * * @class * @implements {CompiledExpression} */ export class CompiledFormulaExpression implements CompiledExpression { /** Type identifier for the compiled expression */ type: "CompiledExpression"; /** * Creates a new instance of CompiledFormulaExpression. * * @param {string} expression - The formula expression to compile. * Must be a valid expression that can be parsed by the formula engine. * * @throws {FormulaInterpreterError} When expression syntax is invalid during compilation * @throws {IncorrectSyntax} When expression has incorrect syntax during compilation */ constructor(expression: string); /** * Evaluates the compiled expression with the provided data. * * @template T - The type of the data object containing variables * @param {T} data - The data object to evaluate the expression against. * Should contain all variables referenced in the expression. * @returns {string | number} The result of the evaluation * * @example * ```typescript * const expr = new CompiledFormulaExpression("price * quantity"); * expr.evaluate({ price: 10, quantity: 5 }); // 50 * ``` * * @throws {FormulaVariableNotFoundError} When required variables are missing from data */ evaluate<T extends DataType>(data: T): string | number; /** * Returns the string representation of the original expression. * * @returns {string} The original expression string that was compiled */ toString(): string; } /** * Regular expressions used for parsing formula expressions. */ export const REGEX: { /** Global regex for matching operators in formulas */ formulaOperatorG: RegExp; /** Single match regex for operators */ formulaOperator: RegExp; /** Regex to identify formula field names (prefixed with 'f_') */ formulaFieldName: RegExp; }; /** * Enumeration for boolean condition results in expressions. * Used for ternary operations and logical evaluations. */ export const ConditionResult: { /** Represents true (evaluates to 1 in numeric context) */ readonly True: 1; /** Represents false (evaluates to 0 in numeric context) */ readonly False: 0; }; /** Addition operator (+) */ export const AdditionOperator = "+"; /** Subtraction operator (-) */ export const SubtractionOperator = "-"; /** Division operator (/) */ export const DivisionOperator = "/"; /** Multiplication operator (*) */ export const MultiplicationOperator = "*"; /** Exponential operator (^) */ export const ExponentialOperator = "^"; /** Modulo operator (%) */ export const ModuloOperator = "%"; /** Logical AND operator (&&) */ export const LogicalAndOperator = "&&"; /** Logical OR operator (||) */ export const LogicalOrOperator = "||"; /** Greater than operator (>) */ export const GreaterThanOperator = ">"; /** Less than operator (<) */ export const LessThanOperator = "<"; /** Greater than or equal operator (>=) */ export const GreaterThanOrEqualOperator = ">="; /** Less than or equal operator (<=) */ export const LessThanOrEqualOperator = "<="; /** Equality operator (==) */ export const EqualOperator = "=="; /** Inequality operator (!=) */ export const NotEqualOperator = "!="; /** Assignment operator (=) */ export const AssignmentOperator = "="; /** Opening parenthesis (() */ export const ParenthesisOpenOperator = "("; /** Closing parenthesis ()) */ export const ParenthesisCloseOperator = ")"; /** Colon operator (:) - used in ternary operations */ export const ColonOperator = ":"; /** Question mark operator (?) - used in ternary operations */ export const QuestionMarkOperator = "?"; /** Backslash operator (\) */ export const BackslashOperator = "\\"; /** Array of all comparison operators */ export const ComparisonOperator: readonly [">", "<", "||", "&&", ">=", "<=", "==", "!="]; /** Array of all arithmetic operators */ export const ArithmeticOperator: readonly ["+", "-", "/", "*", "^", "%"]; /** Combined array of arithmetic and comparison operators plus ternary operator */ export const Operators: readonly ["+", "-", "/", "*", "^", "%", ">", "<", "||", "&&", ">=", "<=", "==", "!=", "?"]; /** Array of all operators including parentheses and colon */ export const AllOperators: readonly ["+", "-", "/", "*", "^", "%", ">", "<", "||", "&&", ">=", "<=", "==", "!=", "?", ":", ")", "("]; /** Priority 1 operators (lowest precedence): addition and subtraction */ export const Priority_1_Operator: readonly ["+", "-"]; /** Priority 2 operators: multiplication, division, modulo */ export const Priority_2_Operator: readonly ["/", "*", "%"]; /** Priority 3 operators (highest precedence): exponentiation */ export const Priority_3_Operator: readonly ["^"]; /** Priority 4 operators: comparisons and ternary */ export const Priority_4_Operator: readonly [">", "<", "||", "&&", ">=", "<=", "==", "!=", "?"]; /** * Represents the data type that can be passed to expression evaluation functions. * Keys are variable names, and values can be numbers, strings, or compiled expressions. */ export type DataType = { [key: string]: number | string | CompiledExpression; }; /** * Array of all supported operators in expressions. */ const OperatorValue: string[]; /** * Represents the supported operators in the expression. * Includes arithmetic, comparison, logical, and ternary operators. */ export type Operator = (typeof OperatorValue)[number]; export {}; /** * Evaluates a mathematical expression and returns the result. * * This function parses and interprets a mathematical formula represented as a string, * applying dynamic values from a given object to resolve variables or conditions within the expression. * * @template T - A generic type representing the structure of the input object. Keys are variable names, and values can be numbers, strings, or arrays. * @param {string} expression - The mathematical expression to be evaluated. * Variables in the expression should correspond to keys in the `obj` parameter. * Supports arithmetic (+, -, *, /, ^, %), comparison (>, <, >=, <=, ==, !=), * logical (&&, ||), and ternary (? :) operators. * @param {T} obj - An object containing the values of the variables referenced in the expression. * Can include nested formula variables prefixed with 'f_' and regular data variables. * @returns {number | string} - The result of the evaluated expression, which can be a number or string. * * @example * ```typescript * // Basic arithmetic * SmartCal("2 + 3 * 4"); // 14 * * // With variables * SmartCal("age + 5", { age: 25 }); // 30 * * // With formula variables * SmartCal("f_total", { * f_subtotal: "price * quantity", * f_total: "f_subtotal * 1.2", * price: 10, * quantity: 5 * }); // 60 * ``` * * @throws {FormulaInterpreterError} When expression syntax is invalid or variables are undefined * @throws {IncorrectSyntax} When expression has incorrect syntax * @throws {InvalidFormulaError} When formula is malformed */ export default function SmartCal<T extends DataType>(expression: string, obj?: T): number | string; /** * Validates whether a given expression is a valid formula that can be parsed and evaluated. * * This function performs syntax checking without executing the expression, making it useful * for input validation before evaluation. * * @param {string} expression - The expression string to validate * @returns {boolean} true if the expression is syntactically valid, false otherwise * * @example * ```typescript * isValidExpression("2 + 3 * 4"); // true * isValidExpression("x > 10 ? 'high' : 'low'"); // true * isValidExpression("2 +"); // false - incomplete expression * isValidExpression("(a + b * c"); // false - unmatched parentheses * ``` * * @note This function only checks syntax validity, not semantic correctness (e.g., undefined variables) */ export function isValidExpression(expression: string): boolean; /** * Compiles a formula expression string into a reusable CompiledExpression object. * * Compilation pre-parses the expression into an AST (Abstract Syntax Tree) for improved * performance when evaluating the same expression multiple times with different data. * * @param {string} expression - The formula expression to compile. Must be a valid expression * that can be parsed by the formula engine. * @returns {CompiledExpression} A compiled expression object that can be evaluated multiple times * * @example * ```typescript * // Compile once, evaluate multiple times * const priceCalculator = compile("quantity * unitPrice * (1 - discount)"); * * // Use with different data * priceCalculator.evaluate({ quantity: 5, unitPrice: 10, discount: 0.1 }); // 45 * priceCalculator.evaluate({ quantity: 3, unitPrice: 15, discount: 0.2 }); // 36 * * // Get original expression * console.log(priceCalculator.toString()); // "quantity * unitPrice * (1 - discount)" * ``` * * @throws {FormulaInterpreterError} When expression syntax is invalid * @throws {IncorrectSyntax} When expression has incorrect syntax */ export function compile(expression: string): CompiledExpression; export class FormulaInterpreterError implements Error { message: string; name: string; stack?: string | undefined; constructor(message: string, error?: string); } export class FormulaVariableNotFoundError extends Error { name: string; data: { variableName: string; container: object; }; constructor(message: string, variableName: string, variableContainer: object); getData(): { variableName: string; container: object; }; } export class IncorrectSyntaxError extends Error { name: string; constructor(message: string, exp: string); getData(): { exp: string; }; } export class InvalidFormulaError extends Error { name: string; constructor(message: string, exp: string); getData(): { exp: string; }; }