Filtrex JavaScript Expression Engine

repository·master·Indexed 22 days ago

https://github.com/joewalnes/filtrex

A simple, safe, and fast JavaScript expression engine that compiles string expressions into high-performance functions for filtering, searching, or calculating data. It supports numeric arithmetic, comparisons, boolean logic, and built-in mathematical functions, with the ability to extend the engine using custom functions via compileExpression().

Tokens
1.6K
Snippets
4
Records
7
Agent score
27%

What's inside Filtrex

  1. Quickstart with Filtrex

    master

    Filtrex allows you to compile string expressions into high-performance JavaScript functions. You can use these functions to filter or evaluate data objects at runtime.

    1. Define an expression string (e.g., from a user input field).
    2. Compile the expression using compileExpression(expression).
    3. Execute the resulting function by passing a data object to it.
    // 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
  2. Handle malformed expressions

    master
    If an expression is syntactically incorrect, calling compileExpression() will throw an exception. To provide a good user experience, wrap the compilation in a try...catch block. This allows you to catch errors and provide real-time feedback to the user (e.g., as they type in a search box).
  3. Compile expressions with custom functions

    master

    You can extend the Filtrex expression language by providing a map of custom functions during the compilation step. This allows users to access application-specific logic within their expressions.

    Pass an object as the second argument to compileExpression(expression, customFunctions) where keys are the function names used in the expression and values are the actual JavaScript functions.

    // 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
  4. Reference: Built-in Functions

    master

    Filtrex provides several built-in mathematical and utility functions:

    • abs(x): Absolute value
    • ceil(x): Round floating point up
    • floor(x): Round floating point down
    • log(x): Natural logarithm
    • max(a, b, c...): Max value (variable length of args)
    • min(a, b, c...): Min value (variable length of args)
    • random(): Random floating point from 0.0 to 1.0
    • round(x): Round floating point
    • sqrt(x): Square root
  5. Reference: Supported Expressions and Operators

    master

    Filtrex supports numbers, strings, and external data variables. Boolean logic is applied based on truthy values (non-zero numbers and non-empty strings are true).

    Numeric Arithmetic

    • x + y (Add)
    • x - y (Subtract)
    • x * y (Multiply)
    • x / y (Divide)
    • x % y (Modulo)
    • x ^ y (Power)

    Comparisons

    • x == y (Equals)
    • x < y (Less than)
    • x <= y (Less than or equal to)
    • x > y (Greater than)
    • x >= y (Greater than or equal to)
    • x ~= y (Regular expression match)
    • x in (a, b, c) (Equivalent to x == a or x == b or x == c)
    • x not in (a, b, c) (Equivalent to x != a and x != b and x != c)

    Boolean Logic

    • x or y (Boolean or)
    • x and y (Boolean and)
    • not x (Boolean not)
    • x ? y : z (If boolean x, value y, else z)
    • ( x ) (Explicit operator precedence)
  6. Compile and execute expressions with compileExpression()

    master

    Use compileExpression(expression, extraFunctions?) to transform a string-based expression into an executable JavaScript function. This function takes an object as input and returns a truthy or falsy value based on the expression logic.

    Supported Data Types

    • Numbers: Integers and floating-point numbers (e.g., 43, -1.234).
    • Strings: Quoted strings (e.g., "hello").
    • Variables: References to keys in the input object (e.g., foo, a.b.c).

    Boolean Logic

    Boolean logic is applied to the truthy/falsy value of the data:

    • Truthy: Any non-zero number or any non-empty string.
    • Falsy: Zero or an empty string.

    Operators and Functions

    CategoryOperators / Functions
    Arithmetic+, -, *, /, %, ^ (power)
    Comparison==, <, <=, >, >=, in (a, b, c), not in (a, b, c)
    Logicalor, and, not, x ? y : z (ternary), ( x ) (precedence)
    Mathabs(x), ceil(x), floor(x), log(x), max(a, b, ...), min(a, b, ...), random(), round(x), sqrt(x)
    // Input from user (e.g. search filter)
    let expression = 'transactions <= 5 and abs(profit) > 20.5';
    
    // Compile expression to executable function
    let myfilter = compileExpression(expression);
    
    // Execute function against data objects
    myfilter({transactions: 3, profit: -40.5}); // returns 1 (truthy)
    myfilter({transactions: 3, profit: -14.5}); // returns 0 (falsy)
  7. Add custom functions to expressions

    master

    You can extend the expression engine by providing an extraFunctions object to compileExpression. The keys in this object become the function names available within your expression strings. These functions are called exactly like the built-in math functions (e.g., sqrt(x)).

    // Define custom functions
    const extraFunctions = {
      myFooBarFunction: (x: number) => x * 2
    };
    
    // Use the custom function in an expression
    const expression = 'myFooBarFunction(val) > 10';
    const myfilter = compileExpression(expression, extraFunctions);
    
    // Execute
    myfilter({val: 6}); // returns 1 (since 6 * 2 = 12, and 12 > 10)