### Install Filtrex via NPM Source: https://www.npmjs.com/package/filtrex?activeTab=dependencies Command to install the package using the node package manager. ```bash npm i filtrex ``` -------------------------------- ### Example Expression Syntax Source: https://www.npmjs.com/package/filtrex?activeTab=readme A sample expression demonstrating the supported syntax for filtering data. ```text category == "meal" and (calories * weight > 2000.0 or subcategory in ("cake", "pie")) ``` -------------------------------- ### Install and Compile Expression with Filtrex Source: https://www.npmjs.com/package/filtrex?activeTab=code Install the Filtrex package using npm or pnpm. Then, import the `compileExpression` function and use it to compile a simple expression string into an executable function. ```bash pnpm add filtrex or npm install filtrex ``` ```javascript import { compileExpression } from "filtrex"; const f = compileExpression(`category == "meal"`); ``` -------------------------------- ### Filtrex Expression Example Source: https://www.npmjs.com/package/filtrex?activeTab=versions An example of a simple Filtrex expression that checks if 'transactions' is less than or equal to 5 and the absolute value of 'profit' is greater than 20.5. ```plaintext transactions <= 5 and abs(profit) > 20.5 ``` -------------------------------- ### Compiled Function Representation Source: https://www.npmjs.com/package/filtrex?activeTab=readme An example of how the Filtrex engine internally represents a compiled expression as a JavaScript function. ```javascript (item) => item.transactions <= 5 && Math.abs(item.profit) > 20.5; ``` -------------------------------- ### Filtrex Tutorial Source: https://www.npmjs.com/package/filtrex?activeTab=readme A complete workflow showing expression compilation and execution against data objects. ```javascript import { compileExpression } from "filtrex"; // Input from the user (eg. search filter) const expression = `transactions <= 5 and abs(profit) > 20.5`; // Compile the expression to an executable function const myfilter = compileExpression(expression); // Execute the function on real data myfilter({ transactions: 3, profit: -40.5 }); // → true myfilter({ transactions: 3, profit: -14.5 }); // → false ``` -------------------------------- ### compileExpression Configuration Source: https://www.npmjs.com/package/filtrex Configuring the Filtrex compiler with custom functions, constants, operators, and property resolution logic. ```APIDOC ## compileExpression(expression, options) ### Description Compiles a string expression into an executable function with custom configuration options. ### Parameters #### Request Body - **expression** (string) - Required - The expression string to compile. - **options** (object) - Optional - Configuration object containing: - **extraFunctions** (object) - Map of function names to implementations. - **constants** (object) - Map of constant names to values. - **operators** (object) - Map of operator symbols to custom implementations. - **customProp** (function) - A property function to resolve identifiers with signature (propertyName, get, obj, type). ### Request Example { "expression": "strlen(firstname) > 5", "options": { "extraFunctions": { "strlen": "(s) => s.length" } } } ### Response #### Success Response (200) - **result** (function) - An executable function that accepts a data object and returns the evaluation result. ``` -------------------------------- ### Compile an Expression Source: https://www.npmjs.com/package/filtrex?activeTab=readme Basic usage for importing and compiling a string expression into an executable function. ```javascript import { compileExpression } from "filtrex"; const f = compileExpression(`category == "meal"`); ``` -------------------------------- ### Filtrex Objects and Arrays Source: https://www.npmjs.com/package/filtrex How to work with arrays and objects in the Filtrex expression language. ```APIDOC ## Objects and Arrays in Filtrex ### Arrays - `(a, b, c)`: Defines an array with elements `a`, `b`, and `c`. - `a in b`: Checks if array `a` is a subset of array `b`. ### Objects - `x of y`: Accesses property `x` of object `y`. ``` -------------------------------- ### Filtrex Expression Language Overview Source: https://www.npmjs.com/package/filtrex This section provides an overview of the data types and basic structures supported by the Filtrex expression language. ```APIDOC ## Filtrex Expression Language Data Types Filtrex supports the following data types: - **Numbers**: Integers and floating-point numbers (e.g., `43`, `-1.234`). - **Strings**: Text enclosed in double quotes (e.g., `"hello"`). Special characters like double-quotes and backslashes can be escaped using a backslash (e.g., `" \" \"`). - **Booleans**: `true` and `false`. - **Arrays**: Ordered lists of values enclosed in parentheses (e.g., `(a, b, c)`). - **Objects**: Key-value pairs where keys are strings and values can be any supported type. Properties can be accessed using the `of` operator (e.g., `x of y`). **Note**: Types are not automatically converted. Operations between incompatible types will result in an error (e.g., `1 + true`). External data variables can be represented by identifiers like `foo`, `a.b.c`, or `'foo-bar'`. **BEWARE!** Strings must be double-quoted, while single quotes are reserved for external variables. The notation `a.b.c` refers to `data['a.b.c']`, not a nested property access. ``` -------------------------------- ### Filtrex Expression Syntax Source: https://www.npmjs.com/package/filtrex?activeTab=dependents Overview of the supported syntax, operators, and built-in functions available in Filtrex expressions. ```APIDOC ## Filtrex Expression Syntax ### Description Filtrex supports various data types and operators for building expressions. Note that types are strict and do not auto-convert. ### Supported Types - **Numbers**: Floating point or integers (e.g., 43, -1.234) - **Strings**: Must be double-quoted (e.g., "hello") - **Variables**: External data variables (e.g., foo, a.b.c) ### Operators - **Arithmetic**: +, -, *, /, ^, mod - **Comparisons**: ==, !=, <, <=, >, >=, ~= (regex), in, not in - **Boolean**: or, and, not, if-then-else - **Objects/Arrays**: (a, b, c) for arrays, 'in' for subset check, 'of' for object property access ### Built-in Functions - **Math**: abs(x), ceil(x), floor(x), log(x), log2(x), log10(x), max(...), min(...), round(x), sqrt(x) - **Utility**: empty(x), exists(x) ``` -------------------------------- ### Filtrex Expression Language Overview Source: https://www.npmjs.com/package/filtrex?activeTab=versions This section details the fundamental components of the Filtrex expression language, including supported data types, operators, and functions. ```APIDOC ## Filtrex Expression Language ### Data Types Filtrex supports the following data types: - **Numbers**: Integers and floating-point numbers (e.g., `43`, `-1.234`). - **Strings**: Text enclosed in double quotes (e.g., `"hello"`). Special characters like double-quotes (`"`) and backslashes (`\`) can be escaped. - **Booleans**: `true` and `false`. - **Arrays**: Ordered lists of values enclosed in parentheses (e.g., `(a, b, c)`). - **Objects**: Key-value pairs where keys are strings and values can be any supported type. Properties can be accessed using the `of` operator (e.g., `x of y`). - **External Data Variables**: Represented by identifiers like `foo`, `a.b.c`, or `'foo-bar'`. Note that single quotes are reserved for external variables, while double quotes are for strings. ### Operators #### Numeric Arithmetic - `x + y`: Addition - `x - y`: Subtraction - `x * y`: Multiplication - `x / y`: Division - `x ^ y`: Power - `x mod y`: Modulo (always returns a positive number, e.g., `-1 mod 3 == 2`) #### Comparisons - `x == y`: Equals - `x != y`: Does not equal - `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)` - `x == y <= z`: Chained relation, equivalent to `(x == y and y <= z)` #### Boolean Logic - `x or y`: Boolean OR - `x and y`: Boolean AND - `not x`: Boolean NOT - `if x then y else z`: Conditional expression - `( x )`: Explicit operator precedence #### Objects and Arrays - `(a, b, c)`: Array literal - `a in b`: Checks if array `a` is a subset of array `b` - `x of y`: Accesses property `x` of object `y` ### Built-in Functions - `abs(x)`: Absolute value - `ceil(x)`: Rounds up to the nearest integer - `empty(x)`: Checks if `x` is undefined, null, an empty array, or an empty string - `exists(x)`: Checks if `x` is not undefined or null - `floor(x)`: Rounds down to the nearest integer - `log(x)`: Natural logarithm - `log2(x)`: Logarithm base two - `log10(x)`: Logarithm base ten - `max(a, b, c...)`: Maximum value among arguments - `min(a, b, c...)`: Minimum value among arguments - `round(x)`: Rounds to the nearest integer - `sqrt(x)`: Square root ### Error Handling Filtrex aims to return errors during expression execution rather than throwing exceptions. This allows for safer handling of user-defined filters. Common error types include: - `UnknownOptionError`: An unrecognized option was provided. - `UnexpectedTypeError`: An argument of an incorrect type was passed to a function or operator. - `UnknownFunctionError`: An attempt was made to call an undefined function. - `UnknownPropertyError`: An attempt was made to access a non-existent property. - `Error`: A general parsing error. ``` -------------------------------- ### Custom Operator Implementations Source: https://www.npmjs.com/package/filtrex?activeTab=code Override built-in operators or implement new ones for custom behavior. ```APIDOC ## Custom Operator Implementations Filtrex allows you to override existing operators or define new ones using the `options.operators` setting. ### Example: Overriding '+' and '-' operators ```javascript import { compileExpression } from "filtrex"; import { add, subtract, unaryMinus, matrix } from "mathjs"; const options = { operators: { "+": add, "-": (a, b) => (b == undefined ? unaryMinus(a) : subtract(a, b)), }, }; const data = { a: matrix([1, 2, 3]), b: matrix([-1, 0, 1]) }; compileExpression(`-a + b`, options)(data); // → matrix([-2, -2, -2]) ``` ``` -------------------------------- ### Implement custom property resolution Source: https://www.npmjs.com/package/filtrex?activeTab=readme Use a custom property function to resolve identifiers dynamically. The signature includes the property name, a safe getter, the data object, and the quote type. ```typescript function propFunction( propertyName: string, // name of the property being accessed get: (name: string) => obj[name], // safe getter that retrieves the property from obj obj: any, // the object passed to compiled expression type: "unescaped" | "single-quoted", // whether the symbol was unquoted or enclosed in single quotes ); ``` ```javascript function containsWord(string, word) { // your optimized code } let options = { customProp: (word, _, string) => containsWord(string, word), }; let myfilter = compileExpression("Bob and Alice or Cecil", options); myfilter("Bob is boring"); // → false myfilter("Bob met Alice"); // → true myfilter("Cecil is cool"); // → true ``` -------------------------------- ### Filtrex Operators Source: https://www.npmjs.com/package/filtrex Details on the arithmetic, comparison, and boolean logic operators available in Filtrex. ```APIDOC ## Operators in Filtrex ### Numeric Arithmetic - `x + y`: Add - `x - y`: Subtract - `x * y`: Multiply - `x / y`: Divide - `x ^ y`: Power - `x mod y`: Modulo (always returns a positive number, e.g., `-1 mod 3 == 2`) ### Comparisons - `x == y`: Equals - `x != y`: Does not equal - `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)` - `x == y <= z`: Chained relation, equivalent to `(x == y and y <= z)` ### Boolean Logic - `x or y`: Boolean OR - `x and y`: Boolean AND - `not x`: Boolean NOT - `if x then y else z`: Conditional expression. If boolean `x` is true, returns `y`, otherwise returns `z`. - `( x )`: Explicit operator precedence. ``` -------------------------------- ### Custom Functions Source: https://www.npmjs.com/package/filtrex?activeTab=code Integrate your own JavaScript functions into Filtrex expressions. ```APIDOC ## Custom Functions This section demonstrates how to add custom functions to Filtrex. ### Example ```javascript // Custom function: Return string length. function strlen(s) { return s.length; } let options = { extraFunctions: { strlen }, }; // Compile expression to executable function let myfilter = compileExpression("strlen(firstname) > 5", options); myfilter({ firstname: "Joe" }); // → false myfilter({ firstname: "Joseph" }); // → true ``` ``` -------------------------------- ### Filtrex Built-in Functions Source: https://www.npmjs.com/package/filtrex A list of available built-in functions in Filtrex for various operations. ```APIDOC ## Built-in Functions in Filtrex - `abs(x)`: Absolute value of `x`. - `ceil(x)`: Rounds `x` up to the nearest integer. - `empty(x)`: Returns `true` if `x` is `undefined`, `null`, an empty array, or an empty string; otherwise, returns `false`. - `exists(x)`: Returns `true` if `x` is not `undefined` or `null`; otherwise, returns `false`. - `floor(x)`: Rounds `x` down to the nearest integer. - `log(x)`: Natural logarithm of `x`. - `log2(x)`: Logarithm base two of `x`. - `log10(x)`: Logarithm base ten of `x`. - `max(a, b, c...)`: Returns the maximum value among the provided arguments (variable length). - `min(a, b, c...)`: Returns the minimum value among the provided arguments (variable length). - `round(x)`: Rounds `x` to the nearest integer. - `sqrt(x)`: Square root of `x`. ``` -------------------------------- ### Error Handling Source: https://www.npmjs.com/package/filtrex?activeTab=dependents Details on how Filtrex handles compilation and execution errors. ```APIDOC ## Error Handling ### Description Filtrex distinguishes between compilation errors (which throw) and execution errors (which return the error object). This ensures safe execution of user-defined filters. ### Error Types - **UnknownOptionError**: Unrecognized option provided. - **UnexpectedTypeError**: Type mismatch for function or operator. - **UnknownFunctionError**: Function not defined or not in `extraFunctions`. - **UnknownPropertyError**: Property not found in `data` or `constants`. - **Error**: General parsing error (e.g., malformed expression). ``` -------------------------------- ### Custom Constants Source: https://www.npmjs.com/package/filtrex?activeTab=code Define custom constants that can be used within Filtrex expressions. ```APIDOC ## Custom Constants Define custom constants to be used within Filtrex expressions. These constants take precedence over data properties with the same name. ### Example 1: Using Math constants ```javascript const options = { constants: { pi: Math.PI }, }; const fn = compileExpression(`2 * pi * radius`, options); fn({ radius: 1 / 2 }); // → Math.PI ``` ### Example 2: Constant precedence over data ```javascript const options = { constants: { a: "a_const " } }; const data = { a: "a_data ", b: "b_data " }; // single-quotes give access to data const expr = `'a' + a + 'b' + b`; compileExpression(expr, options)(data); // → "a_data a_const b_data b_data" ``` ``` -------------------------------- ### Custom Property Function Source: https://www.npmjs.com/package/filtrex?activeTab=code Implement a custom property function to control how identifiers are resolved. ```APIDOC ## Custom Property Function A custom property function allows you to define how identifiers in expressions are resolved and assigned values. ### Signature ```javascript function propFunction( propertyName: string, // name of the property being accessed get: (name: string) => obj[name], // safe getter that retrieves the property from obj obj: any, // the object passed to compiled expression type: "unescaped" | "single-quoted", // whether the symbol was unquoted or enclosed in single quotes ); ``` ### Example: Custom string containment check ```javascript function containsWord(string, word) { // your optimized code } let options = { customProp: (word, _, string) => containsWord(string, word), }; let myfilter = compileExpression("Bob and Alice or Cecil", options); myfilter("Bob is boring"); // → false myfilter("Bob met Alice"); // → true myfilter("Cecil is cool"); // → true ``` **Safety Note:** The `get` function returns `undefined` for properties that are defined on the object's prototype, not on the object itself. This is important to prevent potential security vulnerabilities. ``` -------------------------------- ### Define custom constants in Filtrex Source: https://www.npmjs.com/package/filtrex?activeTab=readme Use the constants option to inject values into expressions. Constants take precedence over data properties, but cannot be accessed via single-quoted symbols. ```javascript const options = { constants: { pi: Math.PI }, }; const fn = compileExpression(`2 * pi * radius`, options); fn({ radius: 1 / 2 }); // → Math.PI ``` ```javascript const options = { constants: { a: "a_const " } }; const data = { a: "a_data ", b: "b_data " }; // single-quotes give access to data const expr = `'a' + a + 'b' + b`; compileExpression(expr, options)(data); // → "a_data a_const b_data b_data" ``` -------------------------------- ### Filtrex Error Handling Source: https://www.npmjs.com/package/filtrex Information on how Filtrex handles errors during expression compilation and execution. ```APIDOC ## Errors in Filtrex Filtrex distinguishes between compilation errors (malformed expressions) and execution errors (returned values). ### Compilation Errors Filtrex may throw errors during the compilation phase if an expression is malformed or invalid options are supplied. It is recommended to validate user-provided expressions to provide immediate feedback. ### Execution Errors Filtrex will **not** throw errors during expression execution. Instead, it will return the corresponding error value. This is intentional to prevent unexpected crashes with user-defined filters. ### Error Types - **UnknownOptionError**: An unrecognized option was provided. - **UnexpectedTypeError**: An argument of an incorrect type was passed to a function or operator. - **UnknownFunctionError**: An attempt was made to call an undefined function. - **UnknownPropertyError**: An attempt was made to access a non-existent property. Use `undefined` or `null` for optional properties, or define a `customProp` function. - **Error**: A general error, often from Jison parsing a malformed expression. Many errors include an `I18N_STRING` for internationalization. ``` -------------------------------- ### Use Dot Access Operator in Filtrex Source: https://www.npmjs.com/package/filtrex?activeTab=readme Enables dot notation for property accessors in filter expressions. Import `useDotAccessOperator` and pass it as a `customProp` function to `compileExpression`. ```javascript import { compileExpression, useDotAccessOperator } from "filtrex"; const expr = "foo.bar"; const fn = compileExpression(expr, { customProp: useDotAccessOperator, }); fn({ foo: { bar: 42 } }); // → 42 ``` -------------------------------- ### Define custom functions in Filtrex Source: https://www.npmjs.com/package/filtrex?activeTab=readme Add custom functions to the expression engine by providing them in the extraFunctions option. ```javascript // Custom function: Return string length. function strlen(s) { return s.length; } let options = { extraFunctions: { strlen }, }; // Compile expression to executable function let myfilter = compileExpression("strlen(firstname) > 5", options); myfilter({ firstname: "Joe" }); // → false myfilter({ firstname: "Joseph" }); // → true ``` -------------------------------- ### Implement Custom Property Function in Filtrex Source: https://www.npmjs.com/package/filtrex?activeTab=dependents Define a custom property function to control how identifiers in expressions are resolved. This function receives the property name, a safe getter, the object, and the symbol type. ```javascript function containsWord(string, word) { // your optimized code } let options = { customProp: (word, _, string) => containsWord(string, word), }; let myfilter = compileExpression("Bob and Alice or Cecil", options); myfilter("Bob is boring"); // → false myfilter("Bob met Alice"); // → true myfilter("Cecil is cool"); // → true ``` -------------------------------- ### Override operators in Filtrex Source: https://www.npmjs.com/package/filtrex?activeTab=readme Customize built-in operator behavior by providing custom implementations in the operators option. ```javascript import { compileExpression } from "filtrex"; import { add, subtract, unaryMinus, matrix } from "mathjs"; const options = { operators: { "+": add, "-": (a, b) => (b == undefined ? unaryMinus(a) : subtract(a, b)), }, }; const data = { a: matrix([1, 2, 3]), b: matrix([-1, 0, 1]) }; compileExpression(`-a + b`, options)(data); // → matrix([-2, -2, -2]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.