### Python Expression Example Source: https://github.com/joewalnes/filtrex/blob/master/README.md An example of an expression that could be evaluated by Filtrex, demonstrating logical and arithmetic operations with data fields. ```python category == "meal" and (calories * weight > 2000.0 or subcategory in ("cake", "pie")) ``` -------------------------------- ### Filtrex Compiled JavaScript Function Example Source: https://github.com/joewalnes/filtrex/blob/master/README.md Illustrates the internal JavaScript function generated by Filtrex after compiling an expression. This shows the optimized and safe code that is executed, providing performance comparable to hand-coded JavaScript. ```javascript // Resulting function function(item) { return item.transactions <= 5 && Math.abs(item.profit) > 20.5; } ``` -------------------------------- ### Prevent Prototype Method Calls in Filtrex Source: https://github.com/joewalnes/filtrex/blob/master/test/filtrex-test.html Illustrates a security measure in Filtrex to prevent the execution of prototype methods on function objects. This example attempts to call a constructor's constructor to gain access to global scope and modify a variable, but it's caught by an exception, ensuring safety. ```javascript window.p0wned = false; var evil = compileExpression( 'constructor.constructor.name.replace("",constructor.constructor("window.p0wned=true"))'); try { evil(); fail('Exception should have been thrown'); } catch(expected) {} eq(false, window.p0wned); ``` -------------------------------- ### Backslash Escaping in Filtrex Expressions Source: https://github.com/joewalnes/filtrex/blob/master/test/filtrex-test.html Illustrates how backslashes are handled for escaping within Filtrex expressions. This example shows that a double backslash followed by 'good' correctly evaluates to '\\good' when the input object contains the escaped backslash. ```javascript eq('\\good', compileExpression("`\\" + '\\'")({'\\':'good'})); ``` -------------------------------- ### Filtrex Expression Compilation and Execution (JavaScript) Source: https://github.com/joewalnes/filtrex/blob/master/README.md Demonstrates the basic usage of Filtrex by compiling a user-provided expression string into an executable JavaScript function and then executing it with sample data. It highlights the transformation from a human-readable expression to an efficient function. ```javascript // Input from user (e.g. search filter) var expression = 'transactions <= 5 and abs(profit) > 20.5'; // Compile expression to executable function var myfilter = compileExpression(expression); // Execute function myfilter({transactions: 3, profit:-40.5}); // returns 1 myfilter({transactions: 3, profit:-14.5}); // returns 0 ``` -------------------------------- ### Compile and Evaluate Expressions with Filtrex Source: https://github.com/joewalnes/filtrex/blob/master/test/filtrex-test.html Demonstrates how to use compileExpression to parse a string into a function and execute it against a data context. This includes support for math, logic, and variable binding. ```javascript // Simple numeric expression const expr = compileExpression('1 + 2 * 3'); console.log(expr()); // 7 // Binding to data const boundExpr = compileExpression('1 + foo * bar'); console.log(boundExpr({foo: 5, bar: 2})); // 11 // Math functions const mathExpr = compileExpression('abs(-5) + ceil(4.1)'); console.log(mathExpr()); // 10 ``` -------------------------------- ### Perform Boolean and Comparison Logic Source: https://github.com/joewalnes/filtrex/blob/master/test/filtrex-test.html Shows how to handle conditional logic, comparisons, and set membership within Filtrex expressions. ```javascript // Boolean logic const logic = compileExpression('1 and 0 or not 0'); console.log(logic()); // 1 // Comparisons and set membership const check = compileExpression('foo in (1, 2, 3)'); console.log(check({foo: 2})); // 1 ``` -------------------------------- ### Handle Filtrex Expression Errors in JavaScript Source: https://context7.com/joewalnes/filtrex/llms.txt Demonstrates how to catch and handle exceptions thrown by `compileExpression` for malformed expressions or unknown functions at runtime. Includes a practical pattern for validating expressions on user input. ```javascript try { var filter = compileExpression('invalid ++ expression'); } catch (e) { console.log('Parse error:', e); // Provide feedback to user that expression is invalid } var expr = compileExpression('unknownFunc(5)'); try { expr({}); } catch (e) { console.log(e); // "Unknown function: unknownFunc()" } function validateExpression(inputElement) { var expression = inputElement.value; if (!expression) { inputElement.style.backgroundColor = '#fff'; // Empty - neutral return null; } try { var compiled = compileExpression(expression); inputElement.style.backgroundColor = '#dfd'; // Valid - green return compiled; } catch (e) { inputElement.style.backgroundColor = '#fdd'; // Invalid - red return null; } } ``` -------------------------------- ### Compile and Execute Custom Function in Filtrex Source: https://github.com/joewalnes/filtrex/blob/master/test/filtrex-test.html Demonstrates how to compile a Filtrex expression that utilizes a custom function. The custom function 'triple' is defined and then made available in the scope for the compiled expression to use. This showcases extensibility by allowing user-defined logic. ```javascript function triple(x) { return x * 3; }; eq(21, compileExpression('triple(v)', {triple:triple})({v:7})); ``` -------------------------------- ### Extending Filtrex with Custom Functions Source: https://context7.com/joewalnes/filtrex/llms.txt Shows how to extend Filtrex's capabilities by defining and registering custom functions. These functions are passed as an object to `compileExpression` and can utilize any JavaScript functionality, providing a secure way to sandbox complex operations. ```javascript // Basic custom function function strlen(s) { return s.length; } var myfilter = compileExpression('strlen(firstname) > 5', {strlen: strlen}); myfilter({firstname: 'Joe'}); // returns 0 (length 3 <= 5) myfilter({firstname: 'Joseph'}); // returns 1 (length 6 > 5) // Multiple custom functions for mathematical plotting var additionalFunctions = { acos: Math.acos, asin: Math.asin, atan: Math.atan, cos: Math.cos, exp: Math.exp, sin: Math.sin, tan: Math.tan }; var plotFunction = compileExpression('sin(x) * cos(x) + 0.5', additionalFunctions); plotFunction({x: 0}); // returns 0.5 plotFunction({x: Math.PI}); // returns 0.5 // Custom function with multiple arguments function between(val, min, max) { return val >= min && val <= max ? 1 : 0; } var rangeFilter = compileExpression('between(price, 10, 50)', {between: between}); rangeFilter({price: 25}); // returns 1 rangeFilter({price: 75}); // returns 0 ``` -------------------------------- ### Adding Custom Functions to Filtrex (JavaScript) Source: https://github.com/joewalnes/filtrex/blob/master/README.md Shows how to extend Filtrex's capabilities by defining and providing custom functions during the expression compilation process. This allows for specialized logic tailored to specific application needs, such as string manipulation. ```javascript // Custom function: Return string length. function strlen(s) { return s.length; } // Compile expression to executable function var myfilter = compileExpression( 'strlen(firstname) > 5', {strlen:strlen}); // custom functions myfilter({firstname:'Joe'}); // returns 0 myfilter({firstname:'Joseph'}); // returns 1 ``` -------------------------------- ### String Comparisons and Regex in Filtrex Source: https://context7.com/joewalnes/filtrex/llms.txt Demonstrates how to perform exact string equality checks and regular expression matching using the `~=` operator within Filtrex expressions. Strings are enclosed in double quotes. ```javascript compileExpression('foo == "hello"')({foo: 'hello'}); // returns 1 compileExpression('foo == "hello"')({foo: 'bye'}); // returns 0 compileExpression('foo != "hello"')({foo: 'bye'}); // returns 1 // Regular expression matching with ~= compileExpression('foo ~= "^[hH]ello"')({foo: 'hello'}); // returns 1 (matches) compileExpression('foo ~= "^[hH]ello"')({foo: 'bye'}); // returns 0 (no match) // Practical regex example: email validation pattern var emailCheck = compileExpression('email ~= "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"'); emailCheck({email: 'user@example.com'}); // returns 1 emailCheck({email: 'invalid-email'}); // returns 0 ``` -------------------------------- ### Filtrex Numeric Arithmetic Operations Source: https://context7.com/joewalnes/filtrex/llms.txt Demonstrates Filtrex's support for standard arithmetic operations including addition, subtraction, multiplication, division, modulo, and exponentiation. Parentheses can be used for grouping. ```javascript // Basic arithmetic compileExpression('1 + 2 * 3')(); // returns 7 compileExpression('(1 + 2) * 3')(); // returns 9 compileExpression('97 % 10')(); // returns 7 (modulo) compileExpression('2 ^ 3')(); // returns 8 (power) compileExpression('1.4 * 1.1')(); // returns 1.54 (floating point) // Complex arithmetic with data binding var calc = compileExpression('(price * quantity) - discount ^ 2'); calc({price: 10, quantity: 5, discount: 2}); // returns 46 ``` -------------------------------- ### Built-in Math Functions in Filtrex Source: https://context7.com/joewalnes/filtrex/llms.txt Explains the usage of Filtrex's built-in mathematical functions, which mirror their JavaScript `Math` object equivalents. These include single-argument functions like `abs`, `ceil`, `floor`, `round`, `sqrt`, `log`, and variable-argument functions like `min` and `max`. ```javascript // Single argument functions compileExpression('abs(-5)')(); // returns 5 compileExpression('ceil(4.1)')(); // returns 5 compileExpression('floor(4.6)')(); // returns 4 compileExpression('round(4.6)')(); // returns 5 compileExpression('sqrt(9)')(); // returns 3 compileExpression('log(10)')(); // returns 2.302... (natural log) // Variable argument functions compileExpression('min(2, 5, 6)')(); // returns 2 compileExpression('max(2, 5, 6)')(); // returns 6 compileExpression('min(2, 5, 6, 1, 9, 12)')(); // returns 1 compileExpression('max(2, 5, 6, 1, 9, 12)')(); // returns 12 // Random number generation compileExpression('random() >= 0')(); // returns 1 (always true) // Practical example: calculate distance var distance = compileExpression('sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2)'); distance({x1: 0, y1: 0, x2: 3, y2: 4}); // returns 5 ``` -------------------------------- ### Filtrex 'in' and 'not in' Operators for Set Membership Source: https://context7.com/joewalnes/filtrex/llms.txt Shows how to use the 'in' and 'not in' operators in Filtrex to check for value existence within a set of values, useful for category filtering and membership tests. ```javascript // Numeric set membership compileExpression('5 in (1, 2, 3, 4)')(); // returns 0 (false) compileExpression('3 in (1, 2, 3, 4)')(); // returns 1 (true) compileExpression('5 not in (1, 2, 3, 4)')(); // returns 1 (true) // String set membership compileExpression('foo in ("aa", "bb")')({foo: 'aa'}); // returns 1 compileExpression('foo not in ("aa", "bb")')({foo: 'cc'}); // returns 1 // Practical example: category filtering var categoryFilter = compileExpression('category in ("electronics", "books", "clothing")'); categoryFilter({category: 'electronics'}); // returns 1 categoryFilter({category: 'food'}); // returns 0 ``` -------------------------------- ### Expression Syntax: In / Not In Operators Source: https://context7.com/joewalnes/filtrex/llms.txt Explains the usage of the `in` and `not in` operators for checking value membership within a set of values, analogous to SQL syntax. This is useful for category filtering and membership tests. ```APIDOC ## Expression Syntax: In / Not In Operators ### Description The `in` and `not in` operators allow checking if a value exists within a set of values, similar to SQL syntax. This is useful for category filtering and membership tests. ### Examples ```javascript // Numeric set membership compileExpression('5 in (1, 2, 3, 4)')(); // returns 0 (false) compileExpression('3 in (1, 2, 3, 4)')(); // returns 1 (true) compileExpression('5 not in (1, 2, 3, 4)')(); // returns 1 (true) // String set membership compileExpression('foo in ("aa", "bb")')({foo: 'aa'}); // returns 1 compileExpression('foo not in ("aa", "bb")')({foo: 'cc'}); // returns 1 // Practical example: category filtering var categoryFilter = compileExpression('category in ("electronics", "books", "clothing")'); categoryFilter({category: 'electronics'}); // returns 1 categoryFilter({category: 'food'}); // returns 0 ``` ``` -------------------------------- ### Data Binding with Symbols in Filtrex Source: https://context7.com/joewalnes/filtrex/llms.txt Illustrates how Filtrex expressions can access external data through symbol names. It covers simple data binding, using dots in symbol names for property access (though not for nested objects), and quoting symbols containing special characters. ```javascript // Simple data binding var expr = compileExpression('1 + foo * bar'); expr({foo: 5, bar: 2}); // returns 11 expr({foo: 2, bar: 1}); // returns 3 // Symbols with dots (flat property access, not nested) compileExpression('hello.world.foo')({'hello.world.foo': 123}); // returns 123 compileExpression('order.gooandstuff')({'order.gooandstuff': 123}); // returns 123 // Quoted symbols for special characters compileExpression("'hello-world-foo'")({'hello-world-foo': 123}); // returns 123 compileExpression("'order+goo*and#stuff'")({'order+goo*and#stuff': 123}); // returns 123 // Undefined properties return undefined safely compileExpression('missingProp')({foo: 1}); // returns undefined ``` -------------------------------- ### Filtrex Boolean Logic and Comparisons Source: https://context7.com/joewalnes/filtrex/llms.txt Illustrates Filtrex's support for boolean operators ('and', 'or', 'not'), comparison operators ('==', '!=', '<', '<=', '>', '>='), and the ternary operator ('? :'). Boolean results are returned as 1 (true) or 0 (false). ```javascript // Comparisons compileExpression('foo == 4')({foo: 4}); // returns 1 compileExpression('foo != 4')({foo: 3}); // returns 1 compileExpression('foo >= 4')({foo: 4}); // returns 1 compileExpression('foo < 4')({foo: 3}); // returns 1 // Boolean logic compileExpression('1 and 1')(); // returns 1 compileExpression('0 or 1')(); // returns 1 compileExpression('not 0')(); // returns 1 compileExpression('(0 and 1) or 1')(); // returns 1 // Ternary operator compileExpression('1 > 2 ? 3 : 4')(); // returns 4 compileExpression('1 < 2 ? 3 : 4')(); // returns 3 // Complex conditional var filter = compileExpression('4 > lowNumber * 2 and (max(a, b) < 20 or foo) ? 1.1 : 9.4'); filter({lowNumber: 1.5, a: 10, b: 12, foo: false}); // returns 1.1 filter({lowNumber: 3.5, a: 10, b: 12, foo: false}); // returns 9.4 ``` -------------------------------- ### Core API: compileExpression Source: https://context7.com/joewalnes/filtrex/llms.txt Compiles a string expression into a reusable JavaScript function. It accepts an expression string and an optional object of custom functions, returning a compiled function that takes a data object and returns the evaluated result. The parser is cached internally for performance. ```APIDOC ## POST /compileExpression ### Description Compiles a string expression into a reusable JavaScript function. It accepts an expression string and an optional object of custom functions, returning a compiled function that takes a data object and returns the evaluated result. The parser is cached internally for performance. ### Method POST ### Endpoint /compileExpression ### Parameters #### Request Body - **expression** (string) - Required - The expression string to compile. - **extraFunctions** (object) - Optional - An object containing custom functions to be used within the expression. ### Request Example ```json { "expression": "transactions <= 5 and abs(profit) > 20.5", "extraFunctions": { "abs": "Math.abs" } } ``` ### Response #### Success Response (200) - **compiledFunction** (function) - A JavaScript function that takes a data object and returns the evaluated result. #### Response Example ```javascript // Assuming the request was for 'transactions <= 5 and abs(profit) > 20.5' var myfilter = response.compiledFunction; myfilter({transactions: 3, profit: -40.5}); // returns 1 (true) myfilter({transactions: 3, profit: -14.5}); // returns 0 (false) ``` ``` -------------------------------- ### Expression Syntax: Numeric Arithmetic Source: https://context7.com/joewalnes/filtrex/llms.txt Demonstrates the use of numeric arithmetic operations within Filtrex expressions, including addition, subtraction, multiplication, division, modulo, exponentiation, and floating-point arithmetic. Parentheses can be used for grouping and operations follow standard mathematical precedence. ```APIDOC ## Expression Syntax: Numeric Arithmetic ### Description Filtrex supports standard arithmetic operations including addition, subtraction, multiplication, division, modulo, and exponentiation. Operations follow standard mathematical precedence rules, with parentheses available for explicit grouping. ### Examples ```javascript // Basic arithmetic compileExpression('1 + 2 * 3')(); // returns 7 compileExpression('(1 + 2) * 3')(); // returns 9 compileExpression('97 % 10')(); // returns 7 (modulo) compileExpression('2 ^ 3')(); // returns 8 (power) compileExpression('1.4 * 1.1')(); // returns 1.54 (floating point) // Complex arithmetic with data binding var calc = compileExpression('(price * quantity) - discount ^ 2'); calc({price: 10, quantity: 5, discount: 2}); // returns 46 ``` ``` -------------------------------- ### Compile and Execute JavaScript Expressions with Filtrex Source: https://context7.com/joewalnes/filtrex/llms.txt Compiles a string expression into a reusable JavaScript function. The compiled function accepts a data object and returns the evaluated result. The parser is cached for performance. ```javascript var expression = 'transactions <= 5 and abs(profit) > 20.5'; var myfilter = compileExpression(expression); // Execute the compiled function with data objects myfilter({transactions: 3, profit: -40.5}); // returns 1 (true) myfilter({transactions: 3, profit: -14.5}); // returns 0 (false) myfilter({transactions: 10, profit: 50}); // returns 0 (false - transactions > 5) // The compiled expression is equivalent to: // function(data) { return data.transactions <= 5 && Math.abs(data.profit) > 20.5; } ``` -------------------------------- ### Preventing Injection with Quoted Names in Filtrex Source: https://github.com/joewalnes/filtrex/blob/master/test/filtrex-test.html Demonstrates Filtrex's protection against injection attacks when dealing with quoted identifiers. It shows that single-quoted names cannot be injected using double quotes, and vice-versa, ensuring that user-provided strings are treated as literal values. ```javascript window.p0wned = false; let evil = compileExpression("`'"+(window.p0wned = true)+"'""); eq(31, evil({'"'+(window.p0wned = true)+'"': 31})); eq(false, window.p0wned); eq(42, compileExpression( "'undefined:(window.p0wned=true)));((true?(x=>x)'()", {'undefined:(window.p0wned=true)));((true?(x=>x)': ()=>42} )()); eq(false, window.p0wned); ``` -------------------------------- ### Expression Syntax: Boolean Logic and Comparisons Source: https://context7.com/joewalnes/filtrex/llms.txt Illustrates the use of boolean operators (`and`, `or`, `not`), comparison operators (`==`, `!=`, `<`, `<=`, `>`, `>=`), and the ternary operator (`? :`) in Filtrex expressions. Boolean results are returned as 1 (true) or 0 (false). ```APIDOC ## Expression Syntax: Boolean Logic and Comparisons ### Description The expression language supports boolean operators (`and`, `or`, `not`) and comparison operators (`==`, `!=`, `<`, `<=`, `>`, `>=`). The ternary operator (`? :`) is available for conditional expressions. Boolean results are returned as 1 (true) or 0 (false). ### Examples ```javascript // Comparisons compileExpression('foo == 4')({foo: 4}); // returns 1 compileExpression('foo != 4')({foo: 3}); // returns 1 compileExpression('foo >= 4')({foo: 4}); // returns 1 compileExpression('foo < 4')({foo: 3}); // returns 1 // Boolean logic compileExpression('1 and 1')(); // returns 1 compileExpression('0 or 1')(); // returns 1 compileExpression('not 0')(); // returns 1 compileExpression('(0 and 1) or 1')(); // returns 1 // Ternary operator compileExpression('1 > 2 ? 3 : 4')(); // returns 4 compileExpression('1 < 2 ? 3 : 4')(); // returns 3 // Complex conditional var filter = compileExpression('4 > lowNumber * 2 and (max(a, b) < 20 or foo) ? 1.1 : 9.4'); filter({lowNumber: 1.5, a: 10, b: 12, foo: false}); // returns 1.1 filter({lowNumber: 3.5, a: 10, b: 12, foo: false}); // returns 9.4 ``` ``` -------------------------------- ### Accessing Data Prototype Properties in Filtrex Source: https://github.com/joewalnes/filtrex/blob/master/test/filtrex-test.html Shows that Filtrex expressions cannot directly access properties of the data prototype. When an expression attempts to access a property 'a' on an object created with a prototype that has 'a', the result is undefined, enforcing data isolation. ```javascript eq(undefined, compileExpression('a')(Object.create({a: 42}))); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.