### Basic Jora Query Examples Source: https://github.com/discoveryjs/jora/blob/master/docs/discovery/text/getting-started.md Demonstrates executing simple Jora queries. The first example shows accessing nested properties, resulting in undefined for missing paths. The second example performs a basic arithmetic operation. ```javascript jora('.foo.bar')({ a: 42 }) // undefined jora('2 + 2')() // 4 ``` -------------------------------- ### Install Jora with npm Source: https://github.com/discoveryjs/jora/blob/master/docs/discovery/text/getting-started.md Install the Jora package using npm for use in your Node.js projects. ```bash npm install jora ``` -------------------------------- ### Defining and Using Custom Jora Methods Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods.md Shows how to define and use custom methods within Jora by extending the query setup. This involves creating a setup with custom methods and then using the custom query factory. ```javascript import jora from 'jora'; // Create a custom setup for queries const queryWithCustomMethods = jora.setup({ methods: { myMethod($) { /* implement custom logic here */ } } }); // Use the custom query factory queryWithCustomMethods('foo.myMethod()')(data, context); ``` -------------------------------- ### reduce() - Explicit Arguments Example Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md Demonstrates the Jora reduce function with explicit arguments, showing the '$' and '$$' order. ```jora reduce(($value, $acc) => $acc + $value, 0) // Result: (depends on input array) ``` -------------------------------- ### Sample Input Data for Event Summary Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md An example JSON object representing the input data for events and users. ```json { "events": [ { "eventName": "Workshop", "eventDetails": "Introduction to Programming", "userId": 1, "timestamp": "2023-01-15T14:00:00Z" }, { "eventName": "Conference", "eventDetails": "Tech Summit", "userId": 2, "timestamp": "2023-01-20T09:00:00Z" }, { "eventName": "Webinar", "eventDetails": "Web Development Basics", "userId": 1, "timestamp": "2023-02-05T18:00:00Z" }, { "eventName": "Workshop", "eventDetails": "Advanced Programming Techniques", "userId": 3, "timestamp": "2023-02-25T14:00:00Z" } ], "users": [ { "id": 1, "name": "Alice", "email": "alice@example.com" }, { "id": 2, "name": "Bob", "email": "bob@example.com" }, { "id": 3, "name": "Carol", "email": "carol@example.com" } ] } ``` -------------------------------- ### Setup Query Factory with Custom Extensions Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/api.md Create a reusable query factory using `jora.setup()` to define custom methods and assertions. This is the recommended and more efficient approach for multiple queries. ```javascript import jora from 'jora'; // Create a custom setup for queries const queryWithCustomMethods = jora.setup({ methods: { myMethod($) { /* method logic here */ } }, assertions: { odd: '$ % 2 = 1' } }); // Use the custom query factory queryWithCustomMethods('foo.myMethod(is odd)')(data, context); ``` -------------------------------- ### Sample Input Data JSON Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md Provides a concrete example of the input data structure for the Jora query. ```json { "books": [ { "id": 1, "title": "The Great Book", "authorId": 101, "tagIds": [201, 202] }, { "id": 2, "title": "A Fantastic Read", "authorId": 102, "tagIds": [202, 203] } ], "authors": [ { "id": 101, "name": "John Doe" }, { "id": 102, "name": "Jane Smith" } ], "tags": [ { "id": 201, "name": "Fiction" }, { "id": 202, "name": "Thriller" }, { "id": 203, "name": "Mystery" } ], "reviews": [ { "bookId": 1, "rating": 5, "text": "An amazing book! I loved every moment of it.", "date": "2023-01-01T00:00:00.000Z" }, { "bookId": 2, "rating": 4, "text": "A captivating story with great characters.", "date": "2023-01-15T00:00:00.000Z" } ] } ``` -------------------------------- ### Jora Function Syntax Examples Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/functions.md Illustrates the basic syntax for defining regular functions in Jora, including functions with no arguments, single arguments, and multiple arguments. ```jora => expr ``` ```jora $arg => expr ``` ```jora () => expr ``` ```jora ($arg) => expr ``` ```jora ($arg1, $arg2) => expr ``` -------------------------------- ### Equivalent jq Query Snippet Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md A partial jq query demonstrating how to map book data, similar to the Jora example. ```jq .books | map({ title: .title, ``` -------------------------------- ### Get Query Suggestions Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/api.md Use the suggestion API to get a list of possible completions for a query at a given position. This aids in query construction and debugging. ```javascript import jora from 'jora'; const query = jora('.[foo=""]', { stat: true }); const statApi = query([{ id: 1, foo: "hello" }, { id: 2, foo: "world" }]); statApi.suggestion(3); // .[f|oo=""] // [ // { // type: 'property', // from: 2, // to: 5, // text: 'foo', // suggestions: [ 'id', 'foo' ] // } // ] statApi.suggestion(7); // .[foo="|"] // [ // { // type: 'value', // from: 6, // to: 8, // text: '""', // suggestions: [ 'hello', 'world' ] // } // ] ``` -------------------------------- ### Array Slice with Step Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/slice-notation.md Extracts elements starting from the beginning with a step of 2. ```jora [1, 2, 3, 4, 5][::2] // Result: [1, 3, 5] ``` -------------------------------- ### Pick Property Values with `.(...)` Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/map.md Use the `.(...)` syntax to extract specific property values from an array of objects. This is a concise way to get an array of values for a given key. ```jora $input: [ { "baz": 1 }, { "baz": 2 }, { "baz": 3 } ]; $input.(baz) // Result: [ 1, 2, 3 ] ``` -------------------------------- ### Jora Example: Sorting Products by Price (Ascending) Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/sort.md Sorts an array of product objects by their 'price' property in ascending order. ```jora $products.sort(price asc) ``` -------------------------------- ### Group by Object Key Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/group.md Groups sales data by currency objects. This example highlights that `group()` can use complex objects as keys, preserving the object identity for grouping. ```javascript const USD = { "code": "USD", "symbol": "$" }; const EUR = { "code": "EUR", "symbol": "€" }; const data = [ { "amount": 100, "currency": USD }, { "amount": 150, "currency": USD }, { "amount": 200, "currency": EUR }, { "amount": 250, "currency": EUR } ]; ``` ```jora .group(=> currency) ``` -------------------------------- ### Jora Example: Sorting Products by Price (Descending) Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/sort.md Sorts an array of product objects by their 'price' property in descending order. ```jora $products.sort(price desc) ``` -------------------------------- ### Custom Method Definition with Function Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/api.md Define a custom method `example` that uses `this.context` and calls other methods/assertions. Requires the method to be declared as a function statement or expression, not an arrow function, to access `this`. ```javascript const customMethods = { example(current, sortingFn = (a, b) => a - b) { if (this.context.value === 'foo' && this.assertion('array', current)) { return this.method('sort', current, sortingFn); } return null; } }; ``` -------------------------------- ### Jora Example: Sorting Users by Age (Asc) and Name (Desc) Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/sort.md Sorts an array of user objects first by 'age' in ascending order, then by 'name' in descending order for users with the same age. ```jora sort(age asc, name desc) ``` -------------------------------- ### Get the sign of a number with sign() Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md The `sign()` method returns `1` for positive numbers, `-1` for negative numbers, and `0` for zero. It preserves the sign of zero. ```jora 5.sign() // Result: 1 ``` ```jora -42 | sign() // Result: -1 ``` ```jora 0.sign() // Result: 0 ``` -------------------------------- ### Pipeline Operator: Nested Usage Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/operators.md An example of nested pipeline operators and variable declarations within a complex query structure. ```jora .({ $bar: num | floor() + ceil() | $ / 2; foo: $bar | a + b, baz: [1, $qux.min() | [$, $]] }) ``` -------------------------------- ### Combining Dot Notation with Filtering and Aggregation Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/dot-notation.md Combine dot notation with filtering and aggregation functions like `sum()` for powerful data manipulation. This example filters items by name and sums their values. ```jora $items: [ { name: 'foo', value: 1 }, { name: 'bar', value: 2 }, { name: 'baz', value: 3 }, { name: 'foo', value: 4 } ]; $items.[name = 'foo'].value.sum() // Result: 5 ``` -------------------------------- ### TypeScript Input Data Definitions Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md Defines the structure for the input data used in the Jora example, including books, authors, tags, and reviews. ```typescript type InputData = { books: Book[]; authors: Author[]; tags: Tag[]; reviews: Review[]; }; type Author = { id: number; name: string; }; type Tag = { id: number; name: string; }; type Book = { id: number; title: string; authorId: number; tagIds: number[]; }; type Review = { bookId: number; rating: number; text: string; date: Date; }; ``` -------------------------------- ### Basic Object Literal Syntax Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/object-literal.md Defines a simple object with string, number, and boolean values. Keys do not require quotes unless they contain special characters, spaces, or start with a digit. ```jora { "name": "John Doe", 'age': 30, isActive: true } ``` -------------------------------- ### Setting Up Jora with Custom Assertions Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/assertions.md Demonstrates how to extend Jora with custom assertions by using the `jora.setup` function. This allows for reusable, custom validation logic. ```javascript import jora from 'jora'; // Setup query factory with custom assertions const createQueryWithCustomAssertions = jora.setup({ assertions: { myAssertion($) { /* test a value */ } } }); // Create a query const queryWithMyAssertion = createQueryWithCustomAssertions('is myAssertion'); ``` -------------------------------- ### Define and Use Variables Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/variables.md Demonstrates basic variable definition and usage, including shorthand for property access. ```jora $foo: 123; $bar; $baz: $foo + $bar; ``` -------------------------------- ### Using Functions from Context Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/functions.md Explains how to use a function provided via context (`#`) by first storing it in a local variable and then calling it as a method. ```jora $functionFromContext: #.someFunction; someValue.$functionFromContext() ``` -------------------------------- ### String Slice with Negative Start to End Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/slice-notation.md Extracts the last two characters of the string. ```jora "hello"[-2:] // Result: "lo" ``` -------------------------------- ### Array Slice with Negative Start to End Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/slice-notation.md Extracts the last two elements of the array. ```jora [1, 2, 3, 4, 5][-2:] // Result: [4, 5] ``` -------------------------------- ### Create and Use a Custom Jora Query Factory Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/api.md Demonstrates how to create a custom query factory with common settings and then use it to create and perform queries. This is useful for applying custom methods or assertions consistently. ```javascript import jora from 'jora'; // Create a query factory with common settings const createQuery = jora.setup({ /* methods, assertions */ }); // Create a query const query = createQuery('foo.bar', { /* options as for jora() without "methods" and "assertions" */ }); // Perform the query const result = query(data, context); ``` -------------------------------- ### String Slice with Start to End Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/slice-notation.md Extracts a substring from the beginning of the string up to index 3 (exclusive). ```jora "hello"[:3] // Result: "hel" ``` -------------------------------- ### Array Slice with Start to End Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/slice-notation.md Extracts elements from the beginning of the array up to index 3 (exclusive). ```jora [1, 2, 3, 4, 5][:3] // Result: [1, 2, 3] ``` -------------------------------- ### Import Jora from unpkg (IIFE) Source: https://github.com/discoveryjs/jora/blob/master/README.md Include the Jora IIFE bundle from unpkg CDN, exporting 'jora' to the global scope. ```html ``` -------------------------------- ### Sample JSON Product Data Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md Provides a sample JSON array of products, each with an id, name, category, price, and a list of tags. ```json { "products": [ { "id": 1, "name": "Product A", "category": "Electronics", "price": 200, "tags": ["trending", "smart", "wireless"] }, { "id": 2, "name": "Product B", "category": "Electronics", "price": 150, "tags": ["smart", "wireless"] }, { "id": 3, "name": "Product C", "category": "Clothing", "price": 50, "tags": ["trending", "fashion"] }, { "id": 4, "name": "Product D", "category": "Clothing", "price": 80, "tags": ["fashion", "casual"] }, { "id": 5, "name": "Product E", "category": "Electronics", "price": 100, "tags": ["trending", "smart"] } ] } ``` -------------------------------- ### Get Object Entries Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md Returns an array of `{ key, value }` objects for each own property of an object, similar to `Object.entries()`. ```jora { a: 42, b: 123 }.entries() // Result: [{ key: 'a', value: 42 }, { key: 'b', value: 123 }] ``` ```jora [1, 2].entries() // Result: [{ key: '0', value: 1 }, { key: '1', value: 2 }] ``` ```jora 'abc'.entries() // Result: [{ key: '0', value: 'a' }, { key: '1', value: 'b' }, { key: '2', value: 'c' }] ``` ```jora 123.entries() // Result: [] ``` -------------------------------- ### String Slice with Start and End Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/slice-notation.md Extracts a substring from index 1 (inclusive) up to index 4 (exclusive). ```jora "hello"[1:4] // Result: "ell" ``` -------------------------------- ### Pick Property Values with Direct Property Access Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/map.md Shows the simplest syntax for picking property values directly, equivalent to `.(...)` and `.map()`. ```jora $input: [ { "baz": 1 }, { "baz": 2 }, { "baz": 3 } ]; $input.baz // Result: [ 1, 2, 3 ] ``` -------------------------------- ### Sample Output Data JSON Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md Illustrates the expected JSON output after applying the Jora query to the sample input data. ```json [ { "title": "The Great Book", "author": "John Doe", "tags": ["Fiction", "Thriller"], "topReview": { "rating": 5, "text": "An amazing book! I loved every moment of it...." } }, { "title": "A Fantastic Read", "author": "Jane Smith", "tags": ["Thriller", "Mystery"], "topReview": { "rating": 4, "text": "A captivating story with great characters...." } } ] ``` -------------------------------- ### Array Slice with Start and End Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/slice-notation.md Extracts elements from index 1 (inclusive) up to index 4 (exclusive). ```jora [1, 2, 3, 4, 5][1:4] // Result: [2, 3, 4] ``` -------------------------------- ### Get Object Keys Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md Returns an array of a given object's own enumerable property names, similar to `Object.keys()`. ```jora { foo: 1, bar: 2 }.keys() // Result: ["foo", "bar"] ``` ```jora [2, 3, 4].keys() // Result: ["0", "1", "2"] ``` ```jora 123.keys() // Result: [] ``` -------------------------------- ### Pick Property Values with `.map()` Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/map.md Demonstrates an alternative method using `.map(=> expr)` to achieve the same result as `.(...)` for picking property values. ```jora $input: [ { "baz": 1 }, { "baz": 2 }, { "baz": 3 } ]; $input.map(=> baz) // Result: [ 1, 2, 3 ] ``` -------------------------------- ### TypeScript Definitions for Event Data Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md Provides TypeScript type definitions for the event and user data structures used in the examples. ```typescript type QueryInput = Event[]; type Event = { eventName: string; eventDetails: string; userId: number; timestamp: string; }; type User = { id: number; name: string; email: string; }; ``` -------------------------------- ### Compute Additional Properties with Spread Syntax Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/map.md Shows how to copy existing properties using the spread syntax (`...`) and compute new properties during mapping. ```jora { "foo": 41 }.({ ..., answer: foo + 1 }) // Result: { "foo": 41, "answer": 42 } ``` -------------------------------- ### Import Jora from CDN (IIFE) Source: https://github.com/discoveryjs/jora/blob/master/README.md Include the Jora IIFE bundle from jsDelivr CDN, exporting 'jora' to the global scope. ```html ``` -------------------------------- ### Import Jora from unpkg (ESM) Source: https://github.com/discoveryjs/jora/blob/master/README.md Import the Jora ES module from unpkg CDN. ```html ``` -------------------------------- ### Filter Files Recursively Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/recursive-map.md Perform filtering after recursive mapping to ensure all relevant data is processed. This example extracts the names of all files. ```jora $ + ..children | .[type = "file"].name ``` -------------------------------- ### Use Jora in Browser (ES Module) Source: https://github.com/discoveryjs/jora/blob/master/README.md Include the Jora ES module bundle for browser usage. ```html ``` -------------------------------- ### Create and Perform a Jora Query Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/api.md This snippet shows the basic usage of the Jora library for creating a query with options and then executing it against data. ```javascript import jora from 'jora'; // Create a query const query = jora('foo.bar', { /* ...options */ }); // Perform the query const result = query(data, context); ``` -------------------------------- ### Core Jora API Usage Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/api.md Demonstrates the fundamental usage of the Jora library for creating and executing queries. ```APIDOC ## Core Jora API Usage ### Description This section covers the basic instantiation and execution of Jora queries. ### Method `jora(query: string, options?: object)` ### Parameters #### Query String - **query** (string) - Required - The Jora query string to be executed. #### Options - **methods** (Object) - Optional - Defines custom methods for use within queries. - **assertions** (Object) - Optional - Specifies custom assertions for use within queries. - **debug** (Boolean or function(name, value)) - Optional - Activates debug output. Defaults to `false`. - **tolerant** (Boolean) - Optional - Enables tolerant parsing mode to suppress parsing errors. Defaults to `false`. - **stat** (Boolean) - Optional - Enables stat mode to provide query statistics instead of results. Defaults to `false`. ### Usage Example ```js import jora from 'jora'; // Create a query const query = jora('foo.bar', { /* ...options */ }); // Perform the query const result = query(data, context); ``` ## Custom Query Factory ### Description This section explains how to create a custom query factory using `jora.setup` for consistent application of custom methods and assertions across multiple queries. ### Method `jora.setup(settings: object)` ### Parameters #### Settings - **methods** (Object) - Optional - Defines custom methods for use within queries. - **assertions** (Object) - Optional - Specifies custom assertions for use within queries. ### Usage Example ```js import jora from 'jora'; // Create a query factory with common settings const createQuery = jora.setup({ /* methods, assertions */ }); // Create a query using the factory const query = createQuery('foo.bar', { /* options as for jora() without "methods" and "assertions" */ }); // Perform the query const result = query(data, context); ``` ``` -------------------------------- ### Apply Operations After Recursive Mapping Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/recursive-map.md Wrap concatenation in parentheses to apply further operations, such as extracting a property, after recursive mapping. This example extracts all 'name' properties. ```jora ($ + ..children).name ``` -------------------------------- ### Pick Object Properties with `.(...)` Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/map.md Map an array of objects and pick specific properties into new objects using the `.(...)` syntax with an object literal. ```jora $input: [ { "foo": "bar", "baz": 1 }, { "foo": "bar", "baz": 2 }, { "foo": "bar", "baz": 3 } ]; $input.({ baz }) // Result: // [ // { "baz": 1 }, // { "baz": 2 }, // { "baz": 3 } // ] ``` -------------------------------- ### Jora Comparison: Using a Function for Sorting Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/sort.md Demonstrates sorting using a JavaScript-like function. Jora uses the function's return value for comparison, defaulting to ascending order. ```jora sort(=> name) ``` -------------------------------- ### Sample Input JSON Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md A sample JSON object representing product data, used as input for the Jora query. ```json { "products": [ { "id": "1", "name": "Product A", "category": "Electronics", "ratings": [4, 5, 4] }, { "id": "2", "name": "Product B", "category": "Electronics", "ratings": [4, 5, 5] }, { "id": "3", "name": "Product C", "category": "Books", "ratings": [3, 4, 3] }, { "id": "4", "name": "Product D", "category": "Books", "ratings": [4, 2, 2] }, { "id": "5", "name": "Product E", "category": "Clothing", "ratings": [4, 4, 5] } ] } ``` -------------------------------- ### Jora Filter Syntax Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/filter.md Demonstrates the basic syntax for filtering in Jora using bracket notation. ```jora .[block] ``` -------------------------------- ### Introspection with Tolerant Mode Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/api.md Combine stat mode with 'tolerant: true' to get suggestions for incomplete queries without compilation errors. This is useful for interactive query building. ```javascript import jora from 'jora'; const query = jora('.[foo=]', { stat: true, tolerant: true // without the tolerant option a query compilation // will raise a parse error: // .[foo=] // ------^ }); const statApi = query([{ id: 1, foo: "hello" }, { id: 2, foo: "world" }]); statApi.suggestion(6); // .[foo=|] // [ // { // type: 'value', // from: 6, // to: 6, // text: '', // suggestions: [ 'hello', 'world' ] // }, // { // type: 'property', // from: 6, // to: 6, // text: '', // suggestions: [ 'id', 'foo' ] // } // ] ``` -------------------------------- ### Get Query Stat Information Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/api.md Use the stat API to retrieve information about values passed through a specific position in the query. This is useful for understanding query execution flow. ```javascript import jora from 'jora'; const query = jora('.[foo=""]', { stat: true }); const statApi = query([{ id: 1, foo: "hello" }, { id: 2, foo: "world" }]); statApi.stat(3); // [ // { // context: 'path', // from: 2, // to: 5, // text: 'foo', // values: Set(2) { [Object], [Object] }, // related: null // } // ] ``` -------------------------------- ### Prevent Infinite Recursion with Transformations Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/recursive-map.md Avoid infinite recursion by applying transformation operations instead of creating new objects or arrays. This example generates numbers from 2 to 5. ```jora 1..($ < 5 ? $ + 1 : []) ``` -------------------------------- ### Comparison Operators: Ordering Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/operators.md Demonstrates the less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=) operators for numerical and string comparisons. ```jora // Less than 1 < 2 // true 2 < 1 // false // Less than or equal to 1 <= 1 // true 2 <= 1 // false // Greater than 2 > 1 // true 1 > 2 // false // Greater than or equal to 2 >= 2 // true 1 >= 2 // false ``` -------------------------------- ### Accessing Nested Properties with Dot Notation Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/dot-notation.md Chain dot notation to access properties at any depth within nested objects. The example demonstrates accessing a deeply nested property. ```jora $person: { name: { first: 'John', last: 'Doe' }, age: 30 }; $person.name.first // Result: 'John' ``` -------------------------------- ### Basic Array Literal Syntax Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/array-literal.md Create a simple array with a list of numbers. ```jora [1, 2, 3, 4, 5] ``` -------------------------------- ### Get the largest integer less than or equal to a number with floor() Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md Use `floor()` to round a number down to the nearest integer. This is useful for integer division or when only the whole number part is needed. ```jora 3.123.floor() // Result: 3 ``` -------------------------------- ### Import Jora (CommonJS) Source: https://github.com/discoveryjs/jora/blob/master/README.md Import the Jora library using CommonJS syntax. ```javascript // CommonJS const jora = require('jora'); ``` -------------------------------- ### Jora Method Syntax Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods.md Illustrates the basic syntax for invoking a method on an expression in Jora. The expression can be omitted. ```jora expr.method(...args) ``` -------------------------------- ### Sample Output Data for Event Summary Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md The expected JSON output after processing the event summary query. ```json [ { "month": "2023-01", "totalEvents": 2, "uniqueUsers": 2 }, { "month": "2023-02", "totalEvents": 2, "uniqueUsers": 2 } ] ``` -------------------------------- ### Import Jora from CDN (ESM) Source: https://github.com/discoveryjs/jora/blob/master/README.md Import the Jora ES module from jsDelivr CDN. ```html ``` -------------------------------- ### Get nearest 32-bit float representation with fround() Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md The `fround()` method returns the nearest single-precision 32-bit float representation of a number. This can be useful for compatibility with systems that use single-precision floats. ```jora 5.5.fround() // Result: 5.5 ``` ```jora 5.05.fround() // Result: 5.050000190734863 ``` -------------------------------- ### Basic Assertion Syntax Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/assertions.md Demonstrates the fundamental syntax for using an assertion in Jora. The expression before 'is' is optional. ```jora expr is assertion ``` ```jora is assertion ``` -------------------------------- ### Using Functions as Method Arguments Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/functions.md Demonstrates how to use a Jora function directly as an argument to a method, such as `group()`, for inline operations. ```jora [1, 2, 3, 4].group(=> $ % 2) // Result: [{ key: 1, value: [1, 3] }, { key: 0, value: [2, 4]}] ``` -------------------------------- ### Group by Property and Map Values (Alternative Syntax) Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/group.md An alternative syntax for grouping by 'region' and extracting 'sales' values, demonstrating flexibility in Jora's query language. ```json [ { "region": "North", "sales": 100 }, { "region": "South", "sales": 200 }, { "region": "East", "sales": 150 }, { "region": "North", "sales": 300 }, { "region": "South", "sales": 250 } ] ``` ```jora .group(=> region).({ key, value: value.(sales) }) ``` -------------------------------- ### Get Absolute Value using Pipeline Operator Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md Returns the absolute value of a number. Note that the unary '-' operator has lower precedence; use grouping or the pipeline operator for negative numbers. ```jora -123 | abs() // Result: 123 ``` ```jora 'hello world'.abs() // Result: NaN ``` -------------------------------- ### Object Literal with Shorthand Syntax for Entries Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/object-literal.md Shows how to use shorthand syntax where the key name is inferred from the value's identifier, method call, or variable. This is equivalent to explicitly assigning the value to a key with the same name. ```jora $city: "New York"; { hello: 'world' } | { hello, $city, size() } // Result: { hello: 'world', city: 'New York', size: 1 } ``` ```jora $city: "New York"; { hello: 'world' } | { hello: hello, city: $city, size: size() } // Result: { hello: 'world', city: 'New York', size: 1 } ``` ```jora [1, 3, 2] | { min(), max(), sum(), avg() } // Result: { min: 1, max: 3, sum: 6, avg: 2 } ``` ```jora { foo.[x > 5], // equivalent to: `foo: foo | .[x > 5]` bar size() * 2, // equivalent to: `bar: bar | size() * 2` baz is number ?: 0, // equivalent to: `baz: baz | is number ?: 0` $var.size(), // equivalent to: `var: var | .size()` sort() reverse() // equivalent to: `sort: sort() | reverse()` } ``` ```jora [1, 2, 3] | { size() + 10 // equivalent to: `size: size() | +10` } // Result: { size: 10 } ``` -------------------------------- ### Storing Functions as Local Variables Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/functions.md Shows how to define a Jora function and store it in a local variable for reuse, which can then be invoked like a regular method. ```jora $oddEven: => $ % 2; [1, 2, 3, 4].group($oddEven) // Result: [{ key: 1, value: [1, 3] }, { key: 0, value: [2, 4]}] ``` -------------------------------- ### Query Introspection with stat API Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/api.md This snippet demonstrates how to compile a Jora query in stat mode and use the returned stat API to get statistics and suggestions at specific positions within the query. ```APIDOC ## stat API Methods ### `stat(pos: number, includeEmpty?: boolean)` Returns an array of ranges with all the values which are passed through `pos` during performing a query. #### Output Format ```ts stat(): Array<{ context: 'path' | 'key' | 'value' | 'in-value' | 'value-subset' | 'var' | 'assertion', from: number, to: number, text: string, values: Set, related: Set | null }> | null ``` ### `suggestion(pos: number, options?)` Returns suggestion values grouped by a type or `null` if there is no any suggestions. The following `options` are supported (all are optional): - `limit` (default: `Infinity`) – a max number of the values that should be returned for each value type (`"property"`, `"value"`, `"variable"`, `"assertion"`) - `sort` (default: `false`) – a comparator function (should take 2 arguments and return a negative number, `0` or a positive number) for value list sorting, makes sence when `limit` is used - `filter` (default: `function`) – a filter function factory (`pattern => value => `) to discard values from the result when returns a falsy value (default is equivalent to `patttern => value => String(value).toLowerCase().includes(pattern)`) #### Output Format ```ts suggestion(): Array<{ type: 'property' | 'value' | 'variable' | 'assertion', from: number, to: number, text: string, suggestions: Array }> | null ``` ``` -------------------------------- ### Arithmetic Operators: Multiply, Divide, and Modulo Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/operators.md Illustrates the multiplication, division, and modulo operators for numerical operations. ```jora // Multiply numbers 2 * 3 // 6 // Divide numbers 10 / 2 // 5 // Modulo 7 % 3 // 1 ``` -------------------------------- ### Use Jora in Browser (IIFE) Source: https://github.com/discoveryjs/jora/blob/master/README.md Include the Jora IIFE bundle for browser usage and access it via the global 'jora' variable. ```html ``` -------------------------------- ### Pipeline Operator: Simplifying Mapping Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/operators.md Illustrates using the pipeline operator to simplify expressions that would typically involve mapping. ```jora { foo: 1, bar: 2, baz: 3 }.(foo + bar + baz) // Result: 6 ``` ```jora { foo: 1, bar: 2, baz: 3 } | foo + bar + baz // Result: 6 ``` -------------------------------- ### Pipeline Operator: Basic Usage Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/operators.md Demonstrates the pipeline operator `|` to chain expressions, passing the result of the left side as the input `$` to the right side. ```jora 1.5 | floor() + ceil() // Result: 3 ``` -------------------------------- ### size() - String Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md Returns the length of a string. ```jora "Hello world".size() // Result: 11 ``` -------------------------------- ### Using Reduce with a Function Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/functions.md Demonstrates summing an array using the `reduce()` method in Jora, where the provided function utilizes `$` for the current element and `$$` for the accumulator. ```jora [1, 2, 3, 4].reduce(=> $$ + $, 0) // Result: 10 ``` -------------------------------- ### Import Jora (ESM) Source: https://github.com/discoveryjs/jora/blob/master/README.md Import the Jora library using ECMAScript module syntax. ```javascript // ESM import jora from 'jora'; ``` -------------------------------- ### Using Built-in Jora Methods: group, sort, size Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods.md Demonstrates the usage of common built-in Jora methods for data manipulation. This snippet groups data by name, then processes the grouped records. ```jora group(=> name) .({ name: key, records: value }) .sort(records.size() desc) ``` -------------------------------- ### pick() - Accessing Object Properties Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md Retrieves a property value from an object by its key. Equivalent to bracket notation. ```jora { foo: 1, bar: 2 }.pick('bar') // Result: 2 ``` -------------------------------- ### Equivalent JavaScript Implementation Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md A JavaScript function that replicates the Jora query's logic for identifying popular tags, calculating matches, sorting, and grouping products. ```javascript function getProductsSortedByPopularTags(data) { const popularTags = data.products .flatMap(product => product.tags) .reduce((acc, tag) => { acc[tag] = (acc[tag] || 0) + 1; return acc; }, {}) .entries() .sort((a, b) => b[1] - a[1]) .slice(0, 5) .map(entry => entry[0]); const productsWithPopularTagsCount = data.products.map(product => { const popularTagsMatchCount = product.tags.filter(tag => popularTags.includes(tag)).length; return { ...product, popularTagsMatchCount }; }); const sortedProducts = productsWithPopularTagsCount.sort((a, b) => { if (b.popularTagsMatchCount !== a.popularTagsMatchCount) { return b.popularTagsMatchCount - a.popularTagsMatchCount; } if (a.category !== b.category) { return a.category.localeCompare(b.category); } return a.price - b.price; }); const groupedProducts = sortedProducts.reduce((acc, product) => { if (!acc[product.popularTagsMatchCount]) { acc[product.popularTagsMatchCount] = []; } acc[product.popularTagsMatchCount].push({ name: product.name, category: product.category, price: product.price }); return acc; }, {}); return Object.entries(groupedProducts).map(([popularTagsCount, products]) => ({ popularTagsCount: Number(popularTagsCount), products })); } ``` -------------------------------- ### Arithmetic Operators: Add and Subtract Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/operators.md Demonstrates the addition and subtraction operators. For arrays, addition merges unique elements, while subtraction removes elements. ```jora // Add numbers 1 + 2 // 3 // Add arrays [1, 2, 3] + [2, 3, 4] // [1, 2, 3, 4] // Subtract numbers 10 - 5 // 5 // Subtract arrays [1, 2, 3] - [2, 3] // [1] // Subtract from array [1, 2, 3] - 2 // [1, 3] ``` -------------------------------- ### String Slice with Step Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/slice-notation.md Extracts characters from the beginning of the string with a step of 2. ```jora "hello"[::2] // Result: "hlo" ``` -------------------------------- ### Using Query-Level Variables as Assertions Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/assertions.md Illustrates how to use a Jora variable that returns a function as an assertion. Ensure the variable is indeed a function to avoid errors. ```jora $odd: => $ % 2; [1, 2, 3, 4, 5].({ num: $, odd: is $odd }) // Result: [ // { "num": 1, "odd": true }, // { "num": 2, "odd": false }, // { "num": 3, "odd": true }, // { "num": 4, "odd": false }, // { "num": 5, "odd": true } // ] ``` -------------------------------- ### Assertion with Logical Operators Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/assertions.md Shows how to combine assertions using logical operators like 'not', 'and', and 'or', with parentheses for grouping. ```jora is not assertion ``` ```jora is (assertion and assertion) ``` ```jora is (assertion or not assertion) ``` ```jora is not (assertion and assertion) ``` ```jora is (assertion and (assertion or assertion)) ``` -------------------------------- ### Comparison Operators: Equality and Inequality Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/operators.md Shows the usage of equals (=) and not equals (!=) operators, which perform comparisons similar to JavaScript's Object.is(). ```jora // Equals 1 = 1 // true 'a' = 'b' // false // Not equals 1 != 2 // true 'a' != 'a' // false ``` -------------------------------- ### Variable Usage in Mapping Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/variables.md Shows how to define variables and use them within a mapping operation to transform array elements. ```jora $numbers: [1, 2, 3]; $multiplier: 2; $numbers.($ * $multiplier) ``` -------------------------------- ### Map Primitive Value to Object Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/map.md Demonstrates mapping a primitive value (number) to an object using the `.(...)` syntax. The `$` symbol references the current primitive value. ```jora 123.({ foo: $ }) // Result: { "foo": 123 } ``` -------------------------------- ### Using Stored Functions as Methods Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/functions.md Illustrates calling a Jora function stored as a local variable as if it were a built-in method on a data structure. ```jora $countOdd: => .[$ % 2].size(); [1, 2, 3, 4].$countOdd() // Result: 2 ``` -------------------------------- ### pick() - Accessing Array Elements Source: https://github.com/discoveryjs/jora/blob/master/docs/articles/methods-builtin.md Retrieves an element from an array by its index. Equivalent to bracket notation. ```jora [1, 2, 3, 4].pick(2) // Result: 3 ``` -------------------------------- ### Create and Perform Jora Query Source: https://github.com/discoveryjs/jora/blob/master/README.md Create a Jora query and execute it against data with an optional context. ```javascript import jora from 'jora'; // create a query const query = jora('foo.bar'); // perform a query const result = query(data, context); ``` -------------------------------- ### Equivalent JavaScript Implementation Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md Provides a JavaScript function that replicates the logic of the Jora query for mapping, filtering, and sorting book data. ```javascript function getMappedBooks(inputData, tagFilter) { const { books, authors, tags, reviews } = inputData; const filteredBooks = books .map(book => { const author = authors.find(author => author.id === book.authorId); const bookTags = tags.filter(tag => book.tagIds.includes(tag.id)); const bookReviews = reviews.filter(review => review.bookId === book.id); const sortedReviews = bookReviews.sort((a, b) => { const ratingDiff = b.rating - a.rating; if (ratingDiff !== 0) { return ratingDiff; } return new Date(b.date) - new Date(a.date); }); const topReview = sortedReviews[0] && { rating: sortedReviews[0].rating, text: `${sortedReviews[0].text.slice(0, 150)}...` }; return { title: book.title, author: author.name, tags: bookTags.map(tag => tag.name), topReview: topReview }; }) .filter(mappedBook => tagFilter.some(tag => mappedBook.tags.includes(tag))) .sort((a, b) => { const ratingDiff = b.topReview.rating - a.topReview.rating; if (ratingDiff !== 0) { return ratingDiff; } return a.title.localeCompare(b.title); }); return filteredBooks; } ``` -------------------------------- ### Equivalent JavaScript for Event Summary Source: https://github.com/discoveryjs/jora/blob/master/docs/complex-examples.md A JavaScript implementation that mirrors the logic of the Jora event summary query. ```javascript function processEvents(events, users) { const eventsWithUserDetails = events.map(event => { const userId = event.userId; const user = users.find(user => user.id === userId); return { eventType: event.eventName, eventDate: event.timestamp, eventMonth: event.timestamp.slice(0, 7), userName: user.name, userEmail: user.email }; }); const groupedEvents = eventsWithUserDetails.reduce((acc, event) => { const month = event.eventMonth; if (!acc[month]) { acc[month] = []; } acc[month].push(event); return acc; }, {}); const result = Object.entries(groupedEvents).map(([month, events]) => { const uniqueUsers = new Set(events.map(event => event.userName)).size; return { month, totalEvents: events.length, uniqueUsers }; }); result.sort((a, b) => a.month.localeCompare(b.month)); return result; } ```