### Install comparator.ts using package managers Source: https://github.com/simonkberg/comparator.ts/blob/main/README.md Instructions for installing the comparator.ts library using popular package managers like pnpm, yarn, and npm. No external dependencies are required for installation. ```sh pnpm add comparator.ts # or # yarn add comparator.ts # or # npm install comparator.ts ``` -------------------------------- ### Example Usage of dateComparator Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Variable.dateComparator.md Demonstrates how to use the dateComparator to compare two Date objects. The example shows that when the first date is earlier than the second, a negative number is returned. This confirms the ascending order comparison. ```javascript const result = dateComparator(new Date(2023, 0, 1), new Date(2023, 0, 2)); console.log(result); // Outputs a negative number because the first date is earlier than the second. ``` -------------------------------- ### Define stringComparator for String Comparison (TypeScript) Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Variable.stringComparator.md Declares and provides an example for stringComparator, a Comparator type for strings. It utilizes locale-specific ordering for comparisons. The example demonstrates comparing 'apple' and 'banana', expecting a negative result. ```typescript const stringComparator: Comparator; // Example Usage: const result = stringComparator("apple", "banana"); console.log(result); // Outputs a negative number because "apple" comes before "banana". ``` -------------------------------- ### Create Custom String Length Comparator in TypeScript Source: https://context7.com/simonkberg/comparator.ts/llms.txt Demonstrates how to create a custom string comparator based on length using the `comparator` function. It takes a comparison function and returns a `Comparator` instance. This example shows sorting an array of strings by length. ```typescript import { comparator, type Comparator } from "comparator.ts"; // Create a custom length comparator for strings const lengthComparator: Comparator = comparator( (a, b) => a.length - b.length ); const words = ["elephant", "cat", "dog", "butterfly"]; const sorted = words.sort(lengthComparator); console.log(sorted); // ["cat", "dog", "elephant", "butterfly"] // Can be used with any custom logic const caseInsensitiveComparator = comparator( (a, b) => a.toLowerCase().localeCompare(b.toLowerCase()) ); const names = ["Alice", "bob", "Charlie"]; console.log(names.sort(caseInsensitiveComparator)); // ["Alice", "bob", "Charlie"] ``` -------------------------------- ### Multi-Criteria Sorting for Feature Configurations in TypeScript Source: https://context7.com/simonkberg/comparator.ts/llms.txt Illustrates a comprehensive example of sorting an array of `FeatureConfig` objects using multiple criteria: enabled status, category, priority, and name. It leverages `comparing`, `nullsLast`, `booleanComparator.reversed()`, `stringComparator`, `numberComparator`, and the `thenComparing` method for chained comparisons. The sorting handles optional fields like `enabled` and `priority`. ```typescript import { type Comparator, booleanComparator, comparing, nullsLast, stringComparator } from "comparator.ts"; type FeatureConfig = { enabled?: boolean; name: string; priority?: number; category: string; }; const features: FeatureConfig[] = [ { enabled: false, name: "Feature A", priority: 2, category: "UI" }, { name: "Feature B", category: "Backend" }, { enabled: true, name: "Feature C", priority: 1, category: "UI" }, { enabled: true, name: "Feature D", category: "UI" }, { enabled: false, name: "Feature E", priority: 3, category: "Backend" } ]; // Sort by: enabled (true first), then category, then priority, then name const compareByEnabled: Comparator = comparing( (feature) => feature.enabled, nullsLast(booleanComparator.reversed()) ); const compareByCategory: Comparator = comparing( (feature) => feature.category, stringComparator ); const compareByPriority: Comparator = comparing( (feature) => feature.priority, nullsLast(numberComparator) ); const compareByName: Comparator = comparing( (feature) => feature.name, stringComparator ); const finalComparator = compareByEnabled .thenComparing(compareByCategory) .thenComparing(compareByPriority) .thenComparing(compareByName); const sortedFeatures = features.toSorted(finalComparator); console.log(sortedFeatures); // [ // { enabled: true, name: "Feature C", priority: 1, category: "UI" }, // { enabled: true, name: "Feature D", category: "UI" }, // { enabled: false, name: "Feature A", priority: 2, category: "UI" }, // { enabled: false, name: "Feature E", priority: 3, category: "Backend" }, // { name: "Feature B", category: "Backend" } // ] ``` -------------------------------- ### Compare FeatureConfig array using custom comparators in TypeScript Source: https://github.com/simonkberg/comparator.ts/blob/main/README.md Example demonstrating how to use comparator.ts to sort an array of FeatureConfig objects. It defines custom comparators for 'enabled' and 'name' fields, handling undefined values and using chaining for secondary sorting. Requires the 'comparator.ts' library. ```ts import { type Comparator, booleanComparator, comparing, nullsLast, stringComparator, } from "comparator.ts"; type FeatureConfig = { enabled?: boolean; name: string; }; const data: FeatureConfig[] = [ { enabled: false, name: "Feature A" }, { name: "Feature B" }, { enabled: true, name: "Feature C" }, ]; const compareByEnabled: Comparator = comparing( (feature) => feature.enabled, nullsLast(booleanComparator.reversed()), ); const compareByName: Comparator = comparing( (feature) => feature.name, stringComparator, ); const sortedData = data.toSorted(compareByEnabled.thenComparing(compareByName)); // sortedData = [ // { enabled: true, name: "Feature C" }, // { enabled: false, name: "Feature A" }, // { name: "Feature B" }, // ] ``` -------------------------------- ### Ascending Number Comparison with `numberComparator` in TypeScript Source: https://context7.com/simonkberg/comparator.ts/llms.txt Demonstrates the `numberComparator` for sorting numeric values in ascending order. This comparator works for integers and decimals. The example shows sorting arrays of numbers and performing direct pairwise comparisons. ```typescript import { numberComparator } from "comparator.ts"; const numbers = [42, 8, 15, 23, 4, 16]; const sorted = numbers.sort(numberComparator); console.log(sorted); // [4, 8, 15, 16, 23, 42] // Works with decimals const decimals = [3.14, 2.71, 1.41, 1.73]; console.log(decimals.sort(numberComparator)); // [1.41, 1.73, 2.71, 3.14] // Direct comparison const comparison = numberComparator(10, 20); console.log(comparison); // Negative number (10 < 20) ``` -------------------------------- ### Compare Object Properties with `comparing` in TypeScript Source: https://context7.com/simonkberg/comparator.ts/llms.txt Illustrates using the `comparing` function to create comparators for specific object properties. It requires a function to extract the property and a base comparator for that property type. This example sorts an array of `Person` objects by age and then by name. ```typescript import { comparing, numberComparator, stringComparator } from "comparator.ts"; type Person = { name: string; age: number; city: string; }; const people: Person[] = [ { name: "Alice", age: 30, city: "New York" }, { name: "Bob", age: 25, city: "London" }, { name: "Charlie", age: 35, city: "Paris" }, { name: "David", age: 25, city: "Berlin" } ]; // Sort by age const byAge = comparing( (person) => person.age, numberComparator ); console.log(people.sort(byAge)); // [ // { name: "Bob", age: 25, city: "London" }, // { name: "David", age: 25, city: "Berlin" }, // { name: "Alice", age: 30, city: "New York" }, // { name: "Charlie", age: 35, city: "Paris" } // ] // Sort by name const byName = comparing( (person) => person.name, stringComparator ); console.log(people.sort(byName)); // Sorted alphabetically by name ``` -------------------------------- ### Comparator Methods Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Interface.Comparator.md Details on the methods available for the Comparator interface, including reversed and thenComparing. ```APIDOC ## Methods ### `reversed()` #### Description Creates a comparator that reverses the order of this comparator. #### Method `reversed(): Comparator` #### Endpoint N/A (Method of the Comparator interface) #### Returns `Comparator` - A new Comparator that reverses the order of this comparator. ### `thenComparing(other)` #### Description Creates a compound comparator that first uses this comparator and then uses another comparator if the first comparison results in equality. #### Method `thenComparing(other: Comparator): Comparator` #### Endpoint N/A (Method of the Comparator interface) #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body None #### Parameters (Method Signature) | Parameter | Type | Description | | --------- | ------------------- | ---------------------------------------------------------------------- | | `other` | `Comparator` | Another comparator to use if the first comparison results in equality. | #### Returns `Comparator` - A new Comparator that combines this comparator and the provided comparator. ``` -------------------------------- ### Comparator thenComparing() Method (TypeScript) Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Interface.Comparator.md Creates a compound comparator that chains two comparators. It first uses the current comparator and then uses the provided 'other' comparator if the initial comparison results in equality (0). ```typescript thenComparing(other: Comparator): Comparator; ``` -------------------------------- ### Chaining Comparators with thenComparing Source: https://context7.com/simonkberg/comparator.ts/llms.txt Creates compound comparators by chaining multiple sorting criteria using `thenComparing`. This allows for complex sorting logic, such as sorting by category, then by rating, and finally by price. The `comparing` function is used to create individual comparators based on specified keys and their respective comparators. ```typescript import { comparing, numberComparator, stringComparator, type Comparator } from "comparator.ts"; type Product = { category: string; name: string; price: number; rating: number; }; const products: Product[] = [ { category: "Electronics", name: "Laptop", price: 999, rating: 4.5 }, { category: "Electronics", name: "Mouse", price: 25, rating: 4.5 }, { category: "Books", name: "TypeScript Guide", price: 40, rating: 4.8 }, { category: "Electronics", name: "Keyboard", price: 75, rating: 4.2 }, { category: "Books", name: "JavaScript Basics", price: 30, rating: 4.5 } ]; // Sort by category, then by rating (descending), then by price const byCategory = comparing( (p) => p.category, stringComparator ); const byRating = comparing( (p) => p.rating, numberComparator.reversed() ); const byPrice = comparing( (p) => p.price, numberComparator ); const complexSort: Comparator = byCategory .thenComparing(byRating) .thenComparing(byPrice); console.log(products.sort(complexSort)); ``` -------------------------------- ### Handle Nullable Values with nullsFirst and nullsLast Comparators Source: https://context7.com/simonkberg/comparator.ts/llms.txt Demonstrates how to use `nullsFirst` and `nullsLast` to create comparators that correctly sort arrays containing null or undefined values. These functions wrap existing comparators, specifying whether nulls should appear at the beginning or end of the sorted array. They are useful for sorting data with optional fields. ```typescript import { nullsFirst, nullsLast, numberComparator, stringComparator } from "comparator.ts"; // nullsFirst: null/undefined values sort before non-null values const numbersWithNulls = [5, null, 3, undefined, 1, null, 8]; const nullsFirstSort = nullsFirst(numberComparator); console.log(numbersWithNulls.sort(nullsFirstSort)); // [null, null, undefined, 1, 3, 5, 8] // nullsLast: null/undefined values sort after non-null values const nullsLastSort = nullsLast(numberComparator); console.log([5, null, 3, undefined, 1].sort(nullsLastSort)); // [1, 3, 5, null, undefined] // Complex example with optional fields type User = { name: string; lastLogin?: Date; }; const users: User[] = [ { name: "Alice", lastLogin: new Date("2023-06-15") }, { name: "Bob" }, // no lastLogin { name: "Charlie", lastLogin: new Date("2023-06-20") }, { name: "David" } // no lastLogin ]; const byLastLogin = comparing( (u) => u.lastLogin, nullsLast(dateComparator) ); console.log(users.sort(byLastLogin)); // [ // { name: "Alice", lastLogin: Date("2023-06-15") }, // { name: "Charlie", lastLogin: Date("2023-06-20") }, // { name: "Bob" }, // { name: "David" } // ] ``` -------------------------------- ### Comparator reversed() Method (TypeScript) Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Interface.Comparator.md Creates and returns a new Comparator that reverses the order of the original comparator. This is useful for inverting sort orders. ```typescript reversed(): Comparator; ``` -------------------------------- ### Create Comparator with nullsFirst - TypeScript Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Function.nullsFirst.md The nullsFirst function generates a Comparator that prioritizes null or undefined values, treating them as smaller than any other value. It requires a base comparison function for non-null values. The output is a Comparator that accepts nullable types. ```typescript function nullsFirst(compareFn): Comparator; // Example Usage: // Assuming numberComparator is defined elsewhere: // const result = nullsFirst(numberComparator)(null, 10); // console.log(result); // Outputs a negative number because `null` is considered less than 10. ``` -------------------------------- ### nullsLast() Comparator Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Function.nullsLast.md Creates a comparator function that treats null or undefined values as greater than any other value. It uses a provided comparison function for non-null values. ```APIDOC ## Function: nullsLast() ### Description Creates a [Comparator](Interface.Comparator.md) that considers `null` or `undefined` values as greater than non-null values. ### Type Parameters * `T` - The type of objects to be compared. ### Parameters * `compareFn` (CompareFn) - Required - A function that compares two non-null values of type `T`. Should return a negative number if the first value is less than the second, zero if they are equal, or a positive number if the first is greater. ### Returns Comparator A [Comparator](Interface.Comparator.md) that treats `null` or `undefined` values as greater than non-null values and delegates non-null comparisons to the provided function. ### Example ```typescript const result = nullsLast(numberComparator)(10, null); console.log(result); // Outputs a negative number because 10 is considered less than `null`. ``` ``` -------------------------------- ### Comparator Interface Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Interface.Comparator.md The Comparator interface is used for comparing two objects of type T. It extends the CompareFn interface and has a generic type parameter T. ```APIDOC ## Interface: Comparator ### Description An interface for comparing two objects of type `T`. ### Extends - `CompareFn` ### Type Parameters | Type Parameter | Description | | -------------- | ----------------------------------- | | `T` | The type of objects to be compared. | ### Constructor #### `Comparator(a: T, b: T): number` Defined in: [index.ts:17](https://github.com/simonkberg/comparator.ts/blob/main/index.ts#L17) An interface for comparing two objects of type `T`. #### Parameters | Parameter | Type | Description | | --------- | ---- | ----------- | | `a` | `T` | The first object to compare. | | `b` | `T` | The second object to compare. | #### Returns `number` - A negative value if a < b, zero if a == b, and a positive value if a > b. ``` -------------------------------- ### Create Comparator from Compare Function (TypeScript) Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Function.comparator.md The comparator() function generates a Comparator instance using a provided compareFn. It takes a generic type T and a compareFn as input, returning a Comparator. The compareFn should adhere to the standard comparison function signature, returning negative, zero, or positive values based on the order of two elements. This is useful for defining custom sorting logic. ```TypeScript function comparator(compareFn): Comparator; // Example: const lengthComparator = comparator((a, b) => a.length - b.length); const result = lengthComparator("apple", "banana"); console.log(result); ``` -------------------------------- ### Create nullsLast Comparator (TypeScript) Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Function.nullsLast.md The nullsLast function takes a comparator function for non-null types and returns a new comparator that handles null/undefined values. It's useful for sorting arrays where nulls should be placed at the end. The input is a CompareFn, and the output is a Comparator. ```typescript function nullsLast(compareFn): Comparator; // Example Usage: // Assuming numberComparator is defined elsewhere: // const result = nullsLast(numberComparator)(10, null); // console.log(result); // Outputs a negative number because 10 is considered less than `null`. ``` -------------------------------- ### Define numberComparator for Ascending Number Comparison Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Variable.numberComparator.md Declares a constant 'numberComparator' of type Comparator. This comparator is designed to compare numbers in ascending order. It's a fundamental building block for sorting or ordering numerical data within the comparator.ts library. ```typescript const numberComparator: Comparator; ``` ```typescript const result = numberComparator(10, 20); console.log(result); // Outputs a negative number because 10 is less than 20. ``` -------------------------------- ### Boolean Comparison with booleanComparator Source: https://context7.com/simonkberg/comparator.ts/llms.txt Compares boolean values, treating false as less than true. Useful for sorting tasks or any scenario where boolean order matters. The comparator returns a negative number if the first argument is false and the second is true, a positive number if the first is true and the second is false, and 0 if they are equal. ```typescript import { booleanComparator, comparing } from "comparator.ts"; type Task = { title: string; completed: boolean; }; const tasks: Task[] = [ { title: "Write docs", completed: true }, { title: "Fix bug", completed: false }, { title: "Review PR", completed: true }, { title: "Update tests", completed: false } ]; // Sort by completion status (incomplete first) const byCompletion = comparing( (task) => task.completed, booleanComparator ); console.log(tasks.sort(byCompletion)); // Direct boolean comparison console.log(booleanComparator(false, true)); // Negative number console.log(booleanComparator(true, false)); // Positive number console.log(booleanComparator(true, true)); // 0 ``` -------------------------------- ### Create Comparator by Mapping and Comparing (TypeScript) Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Function.comparing.md The comparing function in comparator.ts creates a Comparator for type T. It utilizes a mapper function to transform objects of type T into values of type U, and then employs a compareFn to compare these mapped U values. This is useful for sorting objects based on a specific property or computed value. ```TypeScript function comparing(mapper, compareFn): Comparator; type Person = { name: string; age: number }; const people: Person[] = [ { name: "Alice", age: 30 }, { name: "Bob", age: 25 }, { name: "Charlie", age: 35 }, ]; const ageComparator = comparing( (person) => person.age, numberComparator, ); const sortedPeople = people.sort(ageComparator); console.log(sortedPeople); // Outputs the array sorted by age in ascending order. ``` -------------------------------- ### Comparator Interface Definition (TypeScript) Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Interface.Comparator.md Defines the Comparator interface for comparing two objects of type T. It extends the CompareFn interface and specifies the signature for a comparison function. ```typescript interface Comparator { (a: T, b: T): number; } ``` -------------------------------- ### Date Comparison with dateComparator Source: https://context7.com/simonkberg/comparator.ts/llms.txt Compares Date objects based on their time values. This is useful for sorting chronological data like events or deadlines. The comparator returns a negative number if the first date is earlier than the second, a positive number if the first date is later, and 0 if they represent the same point in time. ```typescript import { dateComparator, comparing } from "comparator.ts"; const events = [ { name: "Meeting", date: new Date("2023-06-15") }, { name: "Deadline", date: new Date("2023-06-10") }, { name: "Launch", date: new Date("2023-06-20") }, { name: "Review", date: new Date("2023-06-12") } ]; // Sort events chronologically const byDate = comparing( (event) => event.date, dateComparator ); console.log(events.sort(byDate)); // Direct date comparison const date1 = new Date("2023-01-01"); const date2 = new Date("2023-12-31"); console.log(dateComparator(date1, date2)); // Negative number (earlier date) ``` -------------------------------- ### Locale-Aware String Comparison with `stringComparator` in TypeScript Source: https://context7.com/simonkberg/comparator.ts/llms.txt Shows the usage of `stringComparator` for locale-aware string comparison. This comparator handles international characters and special characters correctly according to their locale. It can be used directly with array `sort` or for pairwise comparisons. ```typescript import { stringComparator } from "comparator.ts"; const fruits = ["banana", "apple", "cherry", "date"]; const sorted = fruits.sort(stringComparator); console.log(sorted); // ["apple", "banana", "cherry", "date"] // Works with Unicode and special characters const international = ["Zürich", "Amsterdam", "Ålesund", "Berlin"]; console.log(international.sort(stringComparator)); // Properly handles locale-specific ordering // Check comparison result const result = stringComparator("apple", "banana"); console.log(result); // Negative number (apple < banana) ``` -------------------------------- ### Reversing Sort Order with reversed() Source: https://context7.com/simonkberg/comparator.ts/llms.txt Inverts the comparison order of any existing comparator using the `reversed()` method. This is useful for implementing descending sorts for numbers, reverse alphabetical order for strings, or any other scenario where the default sort order needs to be flipped. It can be applied to built-in comparators like `numberComparator` and `stringComparator`, as well as custom-chained comparators. ```typescript import { numberComparator, stringComparator, comparing } from "comparator.ts"; // Reverse number sorting (descending) const numbers = [1, 5, 3, 9, 2]; console.log(numbers.sort(numberComparator.reversed())); // [9, 5, 3, 2, 1] // Reverse string sorting (Z to A) const names = ["Alice", "Charlie", "Bob"]; console.log(names.sort(stringComparator.reversed())); // ["Charlie", "Bob", "Alice"] // Reverse complex object sorting type Score = { player: string; points: number }; const scores: Score[] = [ { player: "Alice", points: 100 }, { player: "Bob", points: 150 }, { player: "Charlie", points: 120 } ]; const byPoints = comparing( (s) => s.points, numberComparator ); // Sort by highest score first console.log(scores.sort(byPoints.reversed())); // [ // { player: "Bob", points: 150 }, // { player: "Charlie", points: 120 }, // { player: "Alice", points: 100 } // ] ``` -------------------------------- ### Declare dateComparator: Comparator Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Variable.dateComparator.md Declares a constant 'dateComparator' with the type Comparator. This comparator is designed for comparing Date objects chronologically. It's defined in index.ts and can be used to sort or compare dates. ```typescript const dateComparator: Comparator; ``` -------------------------------- ### Declare booleanComparator for Booleans Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/Variable.booleanComparator.md The booleanComparator is a constant of type Comparator. It is used for comparing boolean values in ascending order, where false is treated as less than true. This comparator can be used directly in sorting functions or other comparison-based operations. ```typescript const booleanComparator: Comparator; ``` ```typescript const result = booleanComparator(false, true); console.log(result); // Outputs a negative number because `false` is less than `true`. ``` -------------------------------- ### Define Comparison Function Signature (TypeScript) Source: https://github.com/simonkberg/comparator.ts/blob/main/docs/TypeAlias.CompareFn.md This snippet defines the CompareFn generic type alias in TypeScript. It specifies the signature for a comparison function that takes two arguments of type `T` and returns a number indicating their relative order. This is commonly used for sorting algorithms. ```typescript type CompareFn = (a: T, b: T) => number; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.