{"id":24763501,"url":"https://github.com/andreasnicolaou/typescript-expression-language","last_synced_at":"2025-03-23T14:28:35.655Z","repository":{"id":274250220,"uuid":"922356600","full_name":"andreasnicolaou/typescript-expression-language","owner":"andreasnicolaou","description":"A TypeScript implementation of the popular Symfony Expression Language! This library allows you to evaluate complex expressions client-side, fully mirroring the functionality of the PHP version.","archived":false,"fork":false,"pushed_at":"2025-03-15T09:34:43.000Z","size":411,"stargazers_count":10,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-15T10:27:26.731Z","etag":null,"topics":["expression-language","javascript","php","symfony-expression-language","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/andreasnicolaou.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-01-26T01:12:44.000Z","updated_at":"2025-03-07T17:24:07.000Z","dependencies_parsed_at":"2025-01-26T02:28:22.135Z","dependency_job_id":"3344d58b-eea8-4e73-a510-ced61fa0f934","html_url":"https://github.com/andreasnicolaou/typescript-expression-language","commit_stats":null,"previous_names":["andreasnicolaou/typescript-expression-language"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreasnicolaou%2Ftypescript-expression-language","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreasnicolaou%2Ftypescript-expression-language/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreasnicolaou%2Ftypescript-expression-language/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreasnicolaou%2Ftypescript-expression-language/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andreasnicolaou","download_url":"https://codeload.github.com/andreasnicolaou/typescript-expression-language/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245114908,"owners_count":20563065,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["expression-language","javascript","php","symfony-expression-language","typescript"],"created_at":"2025-01-28T20:31:42.050Z","updated_at":"2025-03-23T14:28:35.623Z","avatar_url":"https://github.com/andreasnicolaou.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# TypeScript Symfony Expression Language\n\nA **TypeScript implementation** of the popular Symfony Expression Language! This library allows you to evaluate complex expressions **client-side**, fully mirroring the functionality of the PHP version.\n\nUse it to create dynamic and flexible expression-based logic on the frontend, perfectly synchronized with the server-side implementation in Symfony/PHP.\n\n![Static Badge](https://img.shields.io/badge/TypeScript-blue)\n![GitHub contributors](https://img.shields.io/github/contributors/andreasnicolaou/typescript-expression-language)\n![GitHub License](https://img.shields.io/github/license/andreasnicolaou/typescript-expression-language)\n![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/andreasnicolaou/typescript-expression-language/build.yaml)\n![GitHub package.json version](https://img.shields.io/github/package-json/v/andreasnicolaou/typescript-expression-language)\n\n![NPM Downloads](https://img.shields.io/npm/dm/%40andreasnicolaou%2Ftypescript-expression-language)\n\n## ![GitHub Repo stars](https://img.shields.io/github/stars/andreasnicolaou/typescript-expression-language)\n\n## ✨ Features\n\n- **Full Symfony Compatibility**: Write expressions that work the same way on both client and server.\n- **Rich Syntax Support**: Includes numbers, strings, operators, functions, and advanced object/array access.\n- **Customizable Operators**: Define your own operators or extend existing ones.\n- **Brackets and Nesting**: Handle deeply nested brackets with accurate syntax validation.\n- **Error Detection**: Detect and report invalid syntax with meaningful error messages.\n- **Word-Based Operators**: Supports expressions like `starts with`, `not in`, `ends with`, `contains`, `matches`, and more!\n- **TypeScript Ready**: Fully typed, ensuring seamless integration into TypeScript projects.\n\n---\n\n## 🚀 Installation\n\n```bash\nnpm install @andreasnicolaou/typescript-expression-language\n```\n\n---\n\n## 🔧 Setup\n\nTo get started, initialize the library in your project:\n\n```typescript\nimport ExpressionLanguage from '@andreasnicolaou/typescript-expression-language';\n\nconst expressionLanguage = new ExpressionLanguage();\n```\n\n---\n\n## 📖 Usage\n\nBasic Evaluation\n\n```typescript\nconst result = expressionLanguage.evaluate('1 + 2');\nconsole.log(result); // Outputs → `3`\n```\n\nMultiple Clauses\n\n```typescript\nconst expression = 'array[2] === \"three\" \u0026\u0026 obj.method(array[1]) === \"value\"';\nconst context = {\n  array: ['one', 'two', 'three'],\n  obj: {\n    method: (arg: string) =\u003e `value`,\n  },\n};\nconst result = expressionLanguage.evaluate(expression, context);  → `true`\nconsole.log(result)  // Outputs → `true`\n```\n\nCustom Functions\n\n```typescript\nexpressionLanguage.registerFunction('toUpperCase', (str: string): string =\u003e str.toUpperCase());\n\nconst expression = 'toUpperCase(\"hello\") === \"HELLO\"';\nconst result = expressionLanguage.evaluate(expression);\nconsole.log(result); // Outputs → `true`\n```\n\n---\n\n## 📋 Supported Syntax\n\n### Operators\n\n#### Arithmetic\n\n- `+`, `-`, `*`, `/`, `%`\n\n#### Comparison\n\n- `==`, `!=`, `\u003c`, `\u003c=`, `\u003e`, `\u003e=`\n\n#### Logical\n\n- `\u0026\u0026`, `||`, `!`\n\n#### Word-Based\n\n- `starts with`, `ends with`, `contains`, `matches`, `not`, `in`, `not in`, `and`, `or`, `xor`\n\n#### Bitwise\n\n- `\u0026`, `|`, `^`, `~`, `\u003c\u003c`, `\u003e\u003e`\n\n---\n\n### Data Access\n\n- **Access array elements**: `array[0]`\n- **Access object properties**: `obj.property`\n- **Call methods**: `obj.method(arg)`\n\n---\n\n### Functions\n\nAdd and register custom functions for flexible application logic.\n\n---\n\n## 🛠️ Built-in Functions\n\nThe library includes a comprehensive set of built-in JavaScript functions to handle various operations. These functions are categorized as follows:\n\n### Array Functions\n\n- `keys`: Returns the keys of an object.  \n  Example: `keys(obj)`\n- `values`: Returns the values of an object.  \n  Example: `values(obj)`\n- `isArray`: Checks if a value is an array.  \n  Example: `isArray(arr)`\n- `concat`: Merges multiple arrays.  \n  Example: `concat(arr1, arr2)`\n- `from`: Creates an array from an iterable.  \n  Example: `from(iterable)`\n- `of`: Creates a new array instance with the given elements.  \n  Example: `of(1, 2, 3)`\n\n---\n\n### String Functions\n\n- `charAt`: Returns the character at a specific index.  \n  Example: `charAt('hello', 1)` → `'e'`\n- `charCodeAt`: Returns the Unicode value of the character at a specific index.  \n  Example: `charCodeAt('A', 0)` → `65`\n- `includes`: Checks if a string contains a substring.  \n  Example: `includes('hello', 'ell')` → `true`\n- `indexOf`: Returns the index of the first occurrence of a substring.  \n  Example: `indexOf('hello', 'e')` → `1`\n- `split`: Splits a string into an array by a separator.  \n  Example: `split('a,b,c', ',')` → `['a', 'b', 'c']`\n- `trim`: Removes whitespace from both ends of a string.  \n  Example: `trim(' hello ')` → `'hello'`\n- `toUpperCase`: Converts a string to uppercase.  \n  Example: `toUpperCase('hello')` → `'HELLO'`\n- `toLowerCase`: Converts a string to lowercase.  \n  Example: `toLowerCase('HELLO')` → `'hello'`\n\n---\n\n### Number Functions\n\n- `isFinite`: Checks if a value is a finite number.  \n  Example: `isFinite(100)` → `true`\n- `isInteger`: Checks if a value is an integer.  \n  Example: `isInteger(100.5)` → `false`\n- `isNaN`: Checks if a value is NaN.  \n  Example: `isNaN(NaN)` → `true`\n- `toFixed`: Formats a number to a fixed number of decimals.  \n  Example: `toFixed(3.14159, 2)` → `'3.14'`\n\n---\n\n### Date Functions\n\n- `now`: Returns the current timestamp.  \n  Example: `now()`\n- `toISOString`: Converts a date to an ISO string.  \n  Example: `toISOString(new Date())`\n- `toDateString`: Converts a date to a readable string.  \n  Example: `toDateString(new Date())`\n- `getTime`: Gets the timestamp of a date.  \n  Example: `getTime(new Date())`\n- `getFullYear`: Returns the year of a date.  \n  Example: `getFullYear(new Date())`\n- `getMonth`: Returns the month of a date (0-based).  \n  Example: `getMonth(new Date())`\n- `getDay`: Returns the day of the week.  \n  Example: `getDay(new Date())`\n- `getMinutes`: Returns the minutes of a date.  \n  Example: `getMinutes(new Date())`\n\n---\n\n### JSON Functions\n\n- `stringify`: Converts a JavaScript object to a JSON string.  \n  Example: `stringify({ key: 'value' })` → `'{\"key\":\"value\"}'`\n- `parse`: Parses a JSON string into an object.  \n  Example: `parse('{\"key\":\"value\"}')` → `{ key: 'value' }`\n\n---\n\n### Regular Expression Functions\n\n- `test`: Tests if a pattern matches a string.  \n  Example: `test(/abc/, 'abcdef')` → `true`\n- `exec`: Executes a pattern and returns the match.  \n  Example: `exec(/abc/, 'abcdef')` → `['abc']`\n\n---\n\n### URI Functions\n\n- `decodeURI`: Decodes a URI.  \n  Example: `decodeURI('%20space')` → `' space'`\n- `encodeURI`: Encodes a URI.  \n  Example: `encodeURI(' space')` → `'%20space'`\n- `decodeURIComponent`: Decodes a URI component.  \n  Example: `decodeURIComponent('%20space')` → `' space'`\n- `encodeURIComponent`: Encodes a URI component.  \n  Example: `encodeURIComponent(' space')` → `'%20space'`\n\n---\n\n### Math Functions\n\nAll functions from JavaScript's `Math` object are included, such as:\n\n- `abs`, `ceil`, `floor`, `round`, `max`, `min`, `random`, `sqrt`, `pow`, `sin`, `cos`, `tan`, etc.\n\n---\n\n## 🛠️ Error Handling\n\nThe library is equipped with robust error detection to ensure smooth debugging of invalid expressions. Below are the common error types and how they are reported:\n\n### 🔄 Common Errors\n\n#### **1. Unmatched Brackets**\n\n- **Description**: The library throws a `SyntaxError` when brackets (`()`, `{}`, `[]`) are unmatched or unbalanced in an expression.\n- **Example**:\n  ```text\n  (a + b\n  ```\n\n#### **2. Invalid Syntax**\n\n- **Description**: The library throws a `SyntaxError` when an expression contains invalid syntax.\n- **Example**:\n  ```text\n  a + b +\n  ```\n\n#### **3. Undefined Variable**\n\n- **Description**: The library throws a `SyntaxError` when it detects an invalid or misplaced character that does not belong to the syntax.\n- **Example**:\n  ```text\n  a + 5 @\n  ```\n\n---\n\n## 🎯 Use Cases\n\nHere are some practical use cases where the TypeScript Symfony Expression Language can be applied:\n\n### **1. Dynamic UI Logic**\n\n- **Description**: Evaluate conditions to dynamically show or hide components based on user input or other variables.\n- **Example**: Show a form field only if a certain checkbox is checked or display a message when specific conditions are met.\n\n### **2. Custom Filters**\n\n- **Description**: Build advanced filtering systems for grids, tables, or reports, allowing users to filter data based on complex expressions.\n- **Example**: Create filters for product listings that use multiple criteria such as price range, availability, or category.\n\n### **3. Formulas and Calculations**\n\n- **Description**: Compute user-defined formulas directly on the client-side, such as calculating discounts, tax rates, or other financial values.\n- **Example**: Allow users to input values in a form and instantly calculate the total cost or apply discounts.\n\n### **4. Interactive Widgets**\n\n- **Description**: Power interactive components (such as sliders, charts, or dashboards) with user-defined expressions for maximum flexibility and real-time updates.\n- **Example**: Use a slider to dynamically adjust a value or a chart that updates based on user-selected filters or criteria.\n\nThese use cases demonstrate how the library can bring advanced, real-time logic directly to the frontend, providing a more interactive and dynamic user experience.\n\n---\n\n## 🛡️ Symfony Compatibility\n\nThis library ensures that expressions written in PHP's **Symfony Expression Language** are fully compatible with the client-side implementation. This enables seamless integration between server-side logic (written in Symfony/PHP) and client-side expression evaluation.\n\n### **Key Benefits:**\n\n- **Consistency**: Expressions behave the same way on both the client and the server.\n- **Synchronization**: Ensure business logic is applied consistently across both sides of the application without discrepancies.\n- **Easy Integration**: Easily synchronize the logic between your PHP backend and TypeScript frontend, without needing separate implementations.\n\nThis compatibility makes it easier to create unified and maintainable applications that share the same logic across the stack.\n\n---\n\n## 📦 Contribution\n\nContributions are welcome! If you encounter issues or have ideas to enhance the library, feel free to submit an **issue** or **pull request**.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreasnicolaou%2Ftypescript-expression-language","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandreasnicolaou%2Ftypescript-expression-language","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreasnicolaou%2Ftypescript-expression-language/lists"}