### Evaluating an Expression with Variables Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Illustrates how to evaluate a parsed mathematical expression using a provided object of variables. The example shows binding 'x' to a value and calculating the result. ```javascript js> expr = Parser.parse("2 ^ x"); (2^x) js> expr.evaluate({ x: 3 }); 8 ``` -------------------------------- ### Substituting Variables in an Expression Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Demonstrates substituting one variable within a parsed expression with another expression or value. The example replaces 'x' with '4 * x' and then evaluates the new expression. ```javascript js> expr = Parser.parse("2 * x + 1"); ((2*x)+1) js> expr.substitute("x", "4 * x"); ((2*(4*x))+1) js> expr2.evaluate({ x: 3 }); 25 ``` -------------------------------- ### Get Symbols (Variables and Functions) - JavaScript Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Returns an array of all symbols in an expression, including variables and any built-in functions used. Similar to `variables()`, it accepts an option `{ withMembers: true }` to include object members in the symbol list. ```javascript js> expr = Parser.parse("min(x, y, z)"); (min(x, y, z)) js> expr.symbols(); min,x,y,z js> expr.simplify({ y: 4, z: 5 }).symbols(); min,x ``` -------------------------------- ### Modify Constants in expr-eval Parser Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Shows how to customize constants available in expr-eval expressions. New constants can be added, or existing ones can be overridden by modifying the `parser.consts` object. Pre-defined constants like E, PI, true, and false are available by default. An example demonstrates adding a custom constant 'R'. ```javascript const parser = new Parser(); parser.consts.R = 1.234; console.log(parser.parse('A+B/R').toString()); // ((A + B) / 1.234) ``` -------------------------------- ### Get Unbound Variables from Expression - JavaScript Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Retrieves an array of unbound variables present in an expression. By default, it returns only top-level variables. An option `withMembers: true` can be used to include chained object members. ```javascript js> expr = Parser.parse("x * (y * atan(1))"); (x*(y*atan(1))) js> expr.variables(); x,y js> expr.simplify({ y: 4 }).variables(); x js> Parser.parse("x.y.z").variables({ withMembers: true }); ['x.y.z'] ``` -------------------------------- ### Basic Usage of expr-eval Parser Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Demonstrates how to parse a mathematical expression and evaluate it with provided variables. It shows two methods: instantiating a Parser and using the static evaluate method. ```javascript const Parser = require('expr-eval').Parser; const parser = new Parser(); let expr = parser.parse('2 * x + 1'); console.log(expr.evaluate({ x: 3 })); // 7 // or Parser.evaluate('6 * x', { x: 7 }) // 42 ``` -------------------------------- ### Parse Expressions with Instance Methods and Customizations - JavaScript Source: https://context7.com/silentmatt/expr-eval/llms.txt Parse an expression using a specific parser instance with custom functions and constants. Add custom functions and constants to the parser instance before parsing. Requires the 'expr-eval' library. ```javascript const Parser = require('expr-eval').Parser; const parser = new Parser(); // Add custom function parser.functions.double = function(x) { return x * 2; }; // Add custom constant parser.consts.MYCONST = 42; // Use custom function and constant const expr = parser.parse('double(x) + MYCONST'); console.log(expr.evaluate({ x: 10 })); // 62 // Multiple custom functions parser.functions.cube = function(x) { return x * x * x; }; parser.functions.average = function(...args) { return args.reduce((a, b) => a + b, 0) / args.length; }; const complexExpr = parser.parse('cube(3) + average(10, 20, 30)'); console.log(complexExpr.evaluate()); // 47 ``` -------------------------------- ### Configure Custom Parser Options - JavaScript Source: https://context7.com/silentmatt/expr-eval/llms.txt Create a parser instance with custom configurations using 'new Parser(options)'. This allows enabling or disabling specific operators like comparison, logical, 'in', and assignment operators. Requires the 'expr-eval' library. ```javascript const Parser = require('expr-eval').Parser; // Disable comparison and logical operators const restrictedParser = new Parser({ operators: { comparison: false, logical: false, 'in': false, assignment: false } }); // This works (math operations enabled) console.log(restrictedParser.evaluate('2 + 3 * 4')); // 14 // Enable specific operators const customParser = new Parser({ operators: { add: true, multiply: true, divide: true, subtract: true, comparison: true, 'in': true, assignment: true } }); // Using 'in' operator const inResult = customParser.evaluate('5 in [1, 5, 10]'); console.log(inResult); // true // Using assignment operator const assigned = customParser.evaluate('x = 10; y = 20; x + y'); console.log(assigned); // 30 ``` -------------------------------- ### Define and Use Custom Functions in JavaScript Source: https://context7.com/silentmatt/expr-eval/llms.txt Demonstrates how to define and use custom functions, including simple functions, functions with multiple parameters, recursive functions, and functions that utilize other defined functions. It also shows how to define functions in one expression and reuse them in subsequent expressions within the same scope. ```javascript const Parser = require('expr-eval').Parser; const parser = new Parser({ operators: { fndef: true } }); // Define and use a simple function const expr1 = parser.parse('square(x) = x * x; square(5)'); console.log(expr1.evaluate({})); // 25 // Define function with multiple parameters const expr2 = parser.parse('add(a, b) = a + b; add(10, 20)'); console.log(expr2.evaluate({})); // 30 // Recursive function (factorial) const expr3 = parser.parse( 'factorial(x) = x < 2 ? 1 : x * factorial(x - 1); factorial(5)' ); console.log(expr3.evaluate({})); // 120 // Multiple function definitions const expr4 = parser.parse( 'double(x) = x * 2; triple(x) = x * 3; double(5) + triple(4)' ); console.log(expr4.evaluate({})); // 22 // Function using other functions const expr5 = parser.parse( 'square(x) = x * x; sumOfSquares(a, b) = square(a) + square(b); sumOfSquares(3, 4)' ); console.log(expr5.evaluate({})); // 25 // Reusing scope across expressions const scope = {}; const def = parser.parse('cube(x) = x * x * x'); def.evaluate(scope); // Defines cube in scope const use = parser.parse('cube(3) + cube(2)'); console.log(use.evaluate(scope)); // 35 ``` -------------------------------- ### Configuring Parser Operators in expr-eval Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Shows how to create a Parser instance with custom operator configurations, disabling default operators like logical and comparison operators while enabling others. ```javascript const parser = new Parser({ operators: { // These default to true, but are included to be explicit add: true, concatenate: true, conditional: true, divide: true, factorial: true, multiply: true, power: true, remainder: true, subtract: true, // Disable and, or, not, <, ==, !=, etc. logical: false, comparison: false, // Disable 'in' and = operators 'in': false, assignment: false } }); ``` -------------------------------- ### Array Operations in JavaScript using expr-eval Source: https://context7.com/silentmatt/expr-eval/llms.txt This snippet demonstrates how to perform various array operations using the expr-eval library. It covers creating array literals, concatenating arrays, and using built-in functions like length, indexOf, join, map, filter, and fold. It also shows how to enable the 'in' operator and perform array indexing. ```javascript const Parser = require('expr-eval').Parser; // Array literals const arr1 = Parser.evaluate('[1, 2, 3, 4, 5]'); console.log(arr1); // [1, 2, 3, 4, 5] // Array concatenation const concat = Parser.evaluate('[1, 2] || [3, 4]'); console.log(concat); // [1, 2, 3, 4] // Array functions const length = Parser.evaluate('length([10, 20, 30, 40])'); console.log(length); // 4 const indexOf = Parser.evaluate('indexOf(3, [1, 2, 3, 4])'); console.log(indexOf); // 2 const join = Parser.evaluate('join(", ", ["a", "b", "c"])'); console.log(join); // "a, b, c" // Using 'in' operator (requires enabling) const parser = new Parser({ operators: { 'in': true } }); const inArray = parser.evaluate('5 in [1, 5, 10, 15]'); console.log(inArray); // true // map function const mapped = Parser.evaluate('map(x -> x * 2, [1, 2, 3, 4])'); console.log(mapped); // [2, 4, 6, 8] // filter function const filtered = Parser.evaluate('filter(x -> x > 5, [3, 7, 2, 9, 4])'); console.log(filtered); // [7, 9] // fold/reduce function const sum = Parser.evaluate('fold((acc, x) -> acc + x, 0, [1, 2, 3, 4])'); console.log(sum); // 10 // Array indexing const indexAccess = Parser.evaluate('[10, 20, 30, 40][2]'); console.log(indexAccess); // 30 ``` -------------------------------- ### Conditional Expressions in JavaScript using expr-eval (Ternary Operator) Source: https://context7.com/silentmatt/expr-eval/llms.txt This snippet illustrates the use of ternary conditional expressions in expr-eval, following the `condition ? trueValue : falseValue` syntax. It covers basic conditionals, usage with variables, nested conditionals, mathematical applications, and integration with other functions. ```javascript const Parser = require('expr-eval').Parser; // Basic conditional const basic = Parser.evaluate('5 > 3 ? 100 : 200'); console.log(basic); // 100 // With variables const withVars = Parser.evaluate('x > 10 ? "high" : "low"', { x: 15 }); console.log(withVars); // "high" // Nested conditionals const nested = Parser.evaluate('x > 10 ? (y > 5 ? 1 : 2) : 3', { x: 15, y: 3 }); console.log(nested); // 2 // Mathematical conditionals const abs = Parser.evaluate('x < 0 ? -x : x', { x: -42 }); console.log(abs); // 42 // Using if function (always evaluates both branches) const ifFunc = Parser.evaluate('if(x > 0, x * 2, x / 2)', { x: 10 }); console.log(ifFunc); // 20 // Complex condition const grade = Parser.evaluate( 'score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"', { score: 85 } ); console.log(grade); // "B" // Conditional with functions const conditional = Parser.evaluate('x > 0 ? sqrt(x) : 0', { x: 16 }); console.log(conditional); // 4 ``` -------------------------------- ### Extend Parser with Custom Functions (JavaScript) Source: https://context7.com/silentmatt/expr-eval/llms.txt Enables extending the expr-eval parser with custom JavaScript functions, allowing for domain-specific operations. Custom functions can accept any number of arguments and return computed values. This includes adding simple functions, functions with multiple parameters, variadic functions, and functions returning objects. Default functions can also be removed. ```javascript const Parser = require('expr-eval').Parser; const parser = new Parser(); // Add simple custom function parser.functions.triple = function(x) { return x * 3; }; console.log(parser.evaluate('triple(7)')); // 21 // Add function with multiple parameters parser.functions.hypotenuse = function(a, b) { return Math.sqrt(a * a + b * b); }; console.log(parser.evaluate('hypotenuse(3, 4)')); // 5 // Add variadic function parser.functions.sumSquares = function(...args) { return args.reduce((sum, x) => sum + x * x, 0); }; console.log(parser.evaluate('sumSquares(1, 2, 3, 4)')); // 30 // Add function returning object (with allowMemberAccess) const objParser = new Parser({ allowMemberAccess: true }); objParser.functions.makePoint = function(x, y) { return { x: x, y: y }; }; const expr = objParser.parse('makePoint(3, 4).x + makePoint(3, 4).y'); console.log(expr.evaluate({})); // 7 // Remove default functions const customParser = new Parser(); delete customParser.functions.random; // Remove random function // Now random() is unavailable in expressions ``` -------------------------------- ### Simplify Expression using JavaScript Source: https://context7.com/silentmatt/expr-eval/llms.txt Simplifies an expression by evaluating constant sub-expressions and replacing variables with their values. This performs partial evaluation without executing function calls, allowing optimization. ```javascript const Parser = require('expr-eval').Parser; // Simplify constant expressions const expr1 = Parser.parse('2 * 4 * x + 1'); const simplified1 = expr1.simplify({}); console.log(simplified1.toString()); // ((8*x)+1) console.log(simplified1.evaluate({ x: 5 })); // 41 // Simplify with variable values const expr2 = Parser.parse('x * (y * atan(1))'); const simplified2 = expr2.simplify({ y: 4 }); console.log(simplified2.toString()); // (x*3.141592653589793) console.log(simplified2.evaluate({ x: 2 })); // 6.283185307179586 // Simplify complex expression const expr3 = Parser.parse('(a + 5) * (b + 3) + c'); const simplified3 = expr3.simplify({ a: 10, b: 7 }); console.log(simplified3.toString()); // (150+c) console.log(simplified3.evaluate({ c: 25 })); // 175 // Simplify arithmetic const expr4 = Parser.parse('100 / 4 + 25 * 2 - 10'); const simplified4 = expr4.simplify({}); console.log(simplified4.toString()); // 65 console.log(simplified4.evaluate({})); // 65 ``` -------------------------------- ### Evaluate Expressions Statically - JavaScript Source: https://context7.com/silentmatt/expr-eval/llms.txt Evaluate a mathematical expression string in a single call using Parser.evaluate(). Supports basic arithmetic, variables, and built-in mathematical functions and array operations. Requires the 'expr-eval' library. ```javascript const Parser = require('expr-eval').Parser; // Basic arithmetic const result = Parser.evaluate('2 + 3 * 4'); console.log(result); // 14 // With variables const withVars = Parser.evaluate('2 * x + y', { x: 5, y: 3 }); console.log(withVars); // 13 // Complex mathematical expression const complex = Parser.evaluate('sin(PI / 4) + cos(PI / 3)', {}); console.log(complex); // 1.2071067811865475 // Using built-in functions const minMax = Parser.evaluate('min(10, 20, 5) + max(1, 8, 3)'); console.log(minMax); // 13 // Array operations const arrayCalc = Parser.evaluate('length([1, 2, 3, 4]) * 2'); console.log(arrayCalc); // 8 ``` -------------------------------- ### Parse Expressions Statically for Re-evaluation - JavaScript Source: https://context7.com/silentmatt/expr-eval/llms.txt Parse an expression string into a reusable Expression object using Parser.parse(). This allows evaluating the same expression multiple times with different variable values. Supports complex expressions and multiple operations. Requires the 'expr-eval' library. ```javascript const Parser = require('expr-eval').Parser; // Parse once, evaluate many times const expr = Parser.parse('2 * x + 1'); console.log(expr.evaluate({ x: 3 })); // 7 console.log(expr.evaluate({ x: 10 })); // 21 console.log(expr.evaluate({ x: -5 })); // -9 // Parse complex expression const formula = Parser.parse('sqrt(x^2 + y^2)'); console.log(formula.evaluate({ x: 3, y: 4 })); // 5 console.log(formula.evaluate({ x: 5, y: 12 })); // 13 // Expression with multiple operations const compound = Parser.parse('a * b + c / d - e'); const result = compound.evaluate({ a: 2, b: 3, c: 8, d: 4, e: 1 }); console.log(result); // 7 ``` -------------------------------- ### Evaluate Expression with Variables using JavaScript Source: https://context7.com/silentmatt/expr-eval/llms.txt Evaluates a parsed mathematical expression using provided variable bindings. Supports simple variables, multiple variables, built-in functions, array variables, and nested object access when enabled. ```javascript const Parser = require('expr-eval').Parser; // Simple evaluation const expr = Parser.parse('2 * x + 1'); console.log(expr.evaluate({ x: 5 })); // 11 // Multiple variables const formula = Parser.parse('(a + b) * (c - d)'); console.log(formula.evaluate({ a: 3, b: 7, c: 15, d: 5 })); // 100 // With built-in functions const trig = Parser.parse('sin(angle) + cos(angle)'); console.log(trig.evaluate({ angle: Math.PI / 4 })); // 1.414213562373095 // Array variables const arrayExpr = Parser.parse('sum(numbers) / length(numbers)'); const avg = arrayExpr.evaluate({ numbers: [10, 20, 30, 40] }); console.log(avg); // 25 // Nested object access (if allowMemberAccess enabled) const parser = new Parser({ allowMemberAccess: true }); const objExpr = parser.parse('obj.x + obj.y'); console.log(objExpr.evaluate({ obj: { x: 5, y: 10 } })); // 15 ``` -------------------------------- ### Add Custom JavaScript Function to expr-eval Parser Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Demonstrates how to add a new function to the expr-eval parser instance. This allows custom logic to be used within evaluated expressions. The new function is added to the `parser.functions` object. Dependencies include the `Parser` class from the expr-eval library. ```javascript const parser = new Parser(); // Add a new function parser.functions.customAddFunction = function (arg1, arg2) { return arg1 + arg2; }; // Remove the factorial function delete parser.functions.fac; parser.evaluate('customAddFunction(2, 4) == 6'); // true //parser.evaluate('fac(3)'); // This will fail ``` -------------------------------- ### Substitute Variable in Expression using JavaScript Source: https://context7.com/silentmatt/expr-eval/llms.txt Creates a new expression by substituting a variable with a number, another expression string, or an Expression object. Useful for function composition and expression transformation. ```javascript const Parser = require('expr-eval').Parser; // Substitute with a number const expr1 = Parser.parse('2 * x + 1'); const expr2 = expr1.substitute('x', 5); console.log(expr2.evaluate({})); // 11 console.log(expr2.toString()); // ((2*5)+1) // Substitute with expression string const expr3 = Parser.parse('2 * x + 1'); const expr4 = expr3.substitute('x', '3 * y'); console.log(expr4.evaluate({ y: 2 })); // 13 console.log(expr4.toString()); // ((2*(3*y))+1) // Substitute with Expression object const base = Parser.parse('a + b'); const substitute = Parser.parse('x * 2'); const result = base.substitute('a', substitute); console.log(result.evaluate({ x: 5, b: 10 })); // 20 console.log(result.toString()); // ((x*2)+b) // Multiple substitutions const multi = Parser.parse('a + b + c'); const step1 = multi.substitute('a', '10'); const step2 = step1.substitute('b', 'x * 2'); console.log(step2.evaluate({ x: 3, c: 5 })); // 21 ``` -------------------------------- ### Extract All Symbols from Expression (JavaScript) Source: https://context7.com/silentmatt/expr-eval/llms.txt Retrieves an array of all symbols (variables and built-in functions) present in an expression. This is useful for understanding expression dependencies. It can optionally include object members if the parser is configured for member access. Constants are not included. ```javascript const Parser = require('expr-eval').Parser; // Variables and functions const expr1 = Parser.parse('min(x, y, z)'); console.log(expr1.symbols()); // ['min', 'x', 'y', 'z'] // Multiple functions const expr2 = Parser.parse('sin(a) + cos(b) + max(c, d)'); console.log(expr2.symbols()); // ['sin', 'cos', 'max', 'a', 'b', 'c', 'd'] // After simplification const expr3 = Parser.parse('min(x, y, z)'); const simplified = expr3.simplify({ y: 4, z: 5 }); console.log(simplified.symbols()); // ['min', 'x'] // With object members const parser = new Parser({ allowMemberAccess: true }); const expr4 = parser.parse('sqrt(obj.x) + obj.y'); console.log(expr4.symbols({ withMembers: true })); // ['sqrt', 'obj.x', 'obj.y'] // Constants are not included as symbols const expr5 = Parser.parse('x + PI + E'); console.log(expr5.symbols()); // ['x'] ``` -------------------------------- ### Compile Expression to JavaScript Function (JavaScript) Source: https://context7.com/silentmatt/expr-eval/llms.txt Transforms an expression into a native JavaScript function for optimized evaluation, especially when the same expression is computed multiple times. This bypasses parsing overhead for performance gains. It supports single or multiple parameters, comma-separated parameter strings, and pre-bound variables. ```javascript const Parser = require('expr-eval').Parser; // Single parameter function const expr1 = Parser.parse('x * 2 + 1'); const func1 = expr1.toJSFunction('x'); console.log(func1(5)); // 11 console.log(func1(10)); // 21 console.log(func1(100)); // 201 // Multiple parameters (array) const expr2 = Parser.parse('x + y + z'); const func2 = expr2.toJSFunction(['x', 'y', 'z']); console.log(func2(1, 2, 3)); // 6 console.log(func2(10, 20, 30)); // 60 // Multiple parameters (comma-separated string) const expr3 = Parser.parse('a * b - c'); const func3 = expr3.toJSFunction('a, b, c'); console.log(func3(5, 4, 3)); // 17 // With pre-bound variables const expr4 = Parser.parse('x + y + z'); const func4 = expr4.toJSFunction('y, z', { x: 100 }); console.log(func4(20, 30)); // 150 console.log(func4(5, 10)); // 115 // Complex mathematical function const expr5 = Parser.parse('sqrt(x^2 + y^2)'); const distance = expr5.toJSFunction('x, y'); console.log(distance(3, 4)); // 5 console.log(distance(5, 12)); // 13 ``` -------------------------------- ### Serialize Expression to String Representation (JavaScript) Source: https://context7.com/silentmatt/expr-eval/llms.txt Converts an expression back into a string, explicitly showing the parse tree structure with parentheses. This is valuable for debugging operator precedence and understanding how expressions are parsed. It handles basic expressions, operator precedence, function calls, substitutions, nested expressions, and array literals. ```javascript const Parser = require('expr-eval').Parser; // Basic expression const expr1 = Parser.parse('2 + 3 * 4'); console.log(expr1.toString()); // (2+(3*4)) // Operator precedence const expr2 = Parser.parse('a + b * c - d / e'); console.log(expr2.toString()); // ((a+(b*c))-(d/e)) // Function calls const expr3 = Parser.parse('sin(x) + cos(y)'); console.log(expr3.toString()); // (sin(x)+cos(y)) // After substitution const expr4 = Parser.parse('x + y'); const substituted = expr4.substitute('x', '2 * z'); console.log(substituted.toString()); // ((2*z)+y) // Nested expressions const expr5 = Parser.parse('(a + b) * (c + d) / (e - f)'); console.log(expr5.toString()); // (((a+b)*(c+d))/(e-f)) // Array literals const expr6 = Parser.parse('[1, 2, 3]'); console.log(expr6.toString()); // ([1, 2, 3]) ``` -------------------------------- ### Configure Parser with Custom Operators - JavaScript Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Demonstrates how to configure the `Parser` with custom operators like 'in' (for array containment) and 'assignment' (for variable assignment). This allows the expression syntax to support extended operations beyond standard arithmetic. ```javascript const parser = new Parser({ operators: { 'in': true, 'assignment': true } }); // Now parser supports 'x in array' and 'y = 2*x' expressions ``` -------------------------------- ### Custom Function Definitions in Expr-Eval (JavaScript) Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Users can define their own functions within the expression scope using the syntax `name(params) = expression`. These functions can accept multiple parameters and are evaluated when called. This allows for creating reusable logic within expressions. ```JavaScript square(x) = x*x add(a, b) = a + b factorial(x) = x < 2 ? 1 : x * factorial(x - 1) ``` -------------------------------- ### Extract Variable Names from Expression using JavaScript Source: https://context7.com/silentmatt/expr-eval/llms.txt Retrieves an array of all unbound variable names within an expression, excluding built-in functions. Useful for validating variable availability before evaluation. Supports options for member access. ```javascript const Parser = require('expr-eval').Parser; // Simple variables const expr1 = Parser.parse('x + y + z'); console.log(expr1.variables()); // ['x', 'y', 'z'] // Variables with functions (functions excluded) const expr2 = Parser.parse('sin(x) + cos(y) + z'); console.log(expr2.variables()); // ['x', 'y', 'z'] // After simplification const expr3 = Parser.parse('x * y * z'); const simplified = expr3.simplify({ y: 5 }); console.log(simplified.variables()); // ['x', 'z'] // Object member access (default: top-level only) const parser = new Parser({ allowMemberAccess: true }); const expr4 = parser.parse('obj.x + obj.y.z'); console.log(expr4.variables()); // ['obj'] // Object member access (with full path) console.log(expr4.variables({ withMembers: true })); // ['obj.x', 'obj.y.z'] // Duplicate variables (returns unique names) const expr5 = Parser.parse('x + x * x'); console.log(expr5.variables()); // ['x'] ``` -------------------------------- ### Define Custom Constants in JavaScript using expr-eval Source: https://context7.com/silentmatt/expr-eval/llms.txt This snippet shows how to define and use custom constants within expressions parsed by expr-eval. Constants are replaced with their values during parsing, allowing for named values in complex calculations. It covers adding numeric and boolean constants, overriding built-in ones, and disabling all constants. ```javascript const Parser = require('expr-eval').Parser; const parser = new Parser(); // Add custom constant parser.consts.LIGHT_SPEED = 299792458; // meters per second parser.consts.PLANCK = 6.62607015e-34; // Planck constant const expr1 = parser.parse('LIGHT_SPEED / 1000'); console.log(expr1.evaluate({})); // 299792.458 (km/s) // Use in complex expressions parser.consts.G = 6.674e-11; // Gravitational constant const gravity = parser.parse('G * m1 * m2 / (r * r)'); const force = gravity.evaluate({ m1: 1000, m2: 2000, r: 10 }); console.log(force); // 1.3348e-6 // Override built-in constants parser.consts.PI = 3.14; // Less precise PI console.log(parser.evaluate('PI * 2')); // 6.28 // Disable all constants const noConstsParser = new Parser(); noConstsParser.consts = {}; // Now E, PI, true, false are unavailable // Add boolean constants parser.consts.DEBUG = true; parser.consts.MAX_RETRIES = 5; const config = parser.parse('DEBUG and x < MAX_RETRIES'); console.log(config.evaluate({ x: 3 })); // true ``` -------------------------------- ### Pre-defined Functions in Expr-Eval Source: https://github.com/silentmatt/expr-eval/blob/master/README.md The library includes several pre-defined functions for mathematical calculations, array manipulation, and conditional logic. Users can also extend this set by binding custom JavaScript functions. Note that the `if` function always evaluates both branches, unlike the ternary operator. ```Expr-Eval random(n) fac(n) min(a,b,...) max(a,b,...) hypot(a,b) pyt(a, b) pow(x, y) atan2(y, x) roundTo(x, n) map(f, a) fold(f, y, a) filter(f, a) indexOf(x, a) join(sep, a) if(c, a, b) ``` -------------------------------- ### Convert Expression to JavaScript Function - JavaScript Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Converts an `Expression` object into a native JavaScript function. Parameters can be specified as an array or a comma-separated string. An optional `variables` object can be provided to pre-simplify the expression with bound values. ```javascript js> expr = Parser.parse("x + y + z"); ((x + y) + z) js> f = expr.toJSFunction("x,y,z"); [Function] // function (x, y, z) { return x + y + z; }; js> f(1, 2, 3) 6 js> f = expr.toJSFunction("y,z", { x: 100 }); [Function] // function (y, z) { return 100 + y + z; }; js> f(2, 3) 105 ``` -------------------------------- ### Simplify Expressions with Variables - JavaScript Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Simplifies constant sub-expressions and replaces variable references with provided literal values. This method performs partial evaluation but does not evaluate function calls (except built-in operators). It's useful for pre-calculating parts of an expression when some variable values are known. ```javascript js> expr = Parser.parse("x * (y * atan(1))").simplify({ y: 4 }); (x*3.141592653589793) js> expr.evaluate({ x: 2 }); 6.283185307179586 ``` -------------------------------- ### Disable Pre-defined Constants in expr-eval Parser Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Illustrates how to disable all pre-defined constants in the expr-eval parser. This is achieved by either replacing or deleting the `parser.consts` object, effectively removing all built-in constants from expression evaluation. ```javascript const parser = new Parser(); parser.consts = {}; ``` -------------------------------- ### Array Literals in Expr-Eval Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Arrays can be constructed directly within expressions using square brackets `[]`. Elements are separated by commas and can include literal values, arithmetic operations, or function calls, including the factorial operator. ```Expr-Eval [ 1, 2, 3, 2+2, 10/2, 3! ] ``` -------------------------------- ### Unary Operators in Expr-Eval Source: https://github.com/silentmatt/expr-eval/blob/master/README.md Expr-Eval supports various unary operators that function similarly to functions but can optionally omit parentheses. These include mathematical operations like negation, absolute value, trigonometric functions, logarithms, and string/array length. The precedence of these operators is lower than exponentiation unless parentheses are used. ```Expr-Eval -x +x x! abs x acos x acosh x asin x asinh x atan x atanh x cbrt x ceil x cos x cosh x exp x expm1 x floor x length x ln x log x log10 x log2 x log1p x not x round x sign x sin x sinh x sqrt x tan x tanh x trunc x ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.