### Install @pallad/compare Source: https://github.com/pallad-ts/compare/blob/master/README.md Installs the @pallad/compare library using npm. This is the first step to using the library in your project. ```shell npm install @pallad/compare ``` -------------------------------- ### Reversing Comparison Order with @pallad/compare Source: https://context7.com/pallad-ts/compare/llms.txt Explains and demonstrates the `compare.reverse` function, which inverts the comparison result. This is particularly useful for implementing descending sort orders in array sorting methods. Examples show direct usage and integration with `Array.sort`. ```typescript import { compare } from '@pallad/compare'; // Normal comparison console.log(compare(1, 2).isLess); // true console.log(compare(1, 2).isGreater); // false // Reversed comparison console.log(compare.reverse(1, 2).isLess); // false console.log(compare.reverse(1, 2).isGreater); // true // Using with Array.sort for descending order const numbers = [5, 1, 10, 3]; const ascending = [...numbers].sort(compare); // [1, 3, 5, 10] const descending = [...numbers].sort(compare.reverse); // [10, 5, 3, 1] ``` -------------------------------- ### Custom Comparator Function with @pallad/compare Source: https://context7.com/pallad-ts/compare/llms.txt Details how to provide a custom comparator function as the third argument to the `compare` function. This allows for flexible comparison logic for any data type, including overriding the default behavior for `Comparable` objects. Examples show using `localeCompare` for string comparison and a numeric comparator. ```typescript import { compare } from '@pallad/compare'; interface Option { type: string; value: string; } // Custom comparator using localeCompare function optionComparator(a: Option, b: Option) { return a.type.localeCompare(b.type); } const option1: Option = { type: '2', value: 'Option 2' }; const option2: Option = { type: '1', value: 'Option 1' }; // Compare with custom comparator console.log(compare(option1, option2, optionComparator).isGreater); // true console.log(compare(option2, option1, optionComparator).isLess); // true // Reverse with custom comparator console.log(compare.reverse(option1, option2, optionComparator).isGreater); // false console.log(compare.reverse(option1, option2, optionComparator).isLess); // true // Comparator can return number or Result directly const numericComparator = (a: number, b: number) => a - b; console.log(compare(5, 10, numericComparator).isLess); // true ``` -------------------------------- ### Create a reusable custom compare function (TypeScript) Source: https://github.com/pallad-ts/compare/blob/master/README.md Demonstrates how to create a reusable comparison function using `createCompareWithComparator`. This function can be used repeatedly without needing to pass the custom comparator each time. ```typescript import {createCompareWithComparator} from '@pallad/compare'; function comparator(a: Option, b: Option) { return a.type.localeCompare(b.type); } const customCompare = createCompareWithComparator(comparator); customCompare(aValue, bValue).isGreater // true customCompare.reverse(aValue, bValue).isGreater // false ``` -------------------------------- ### Implement Comparable interface for custom class (TypeScript) Source: https://github.com/pallad-ts/compare/blob/master/README.md Shows how to implement the `Comparable` interface within a custom class (`Money`) to define its own comparison logic. The `compare` function from the library will automatically use this method when available. ```typescript import {Comparable, Equal, Less, Greater} from '@pallad/compare'; class Money implements Comparable { constructor(readonly value: number, readonly currency: string) { } compare(another: Money) { if (another.currency !== this.currency) { throw new Error('Cannot compare values with different currencies'); } if (another.value === this.value) { return Equal; } else if (this.value < another.value) { return Less } return Greater; } } const amountA = new Money(100, 'BGP'); const amountB = new Money(200, 'BGP'); amountA.compare(amountB) // Less // uses `compare` since it is defined compare(amountA, amountB); // Less ``` -------------------------------- ### Sort an array using compare (TypeScript) Source: https://github.com/pallad-ts/compare/blob/master/README.md Shows how to use the `compare` function as a comparator for the built-in `Array.prototype.sort` method in TypeScript. It also demonstrates how to use `compare.reverse` for descending order sorting. ```typescript import {compare} from '@pallad/compare'; [5, 1, 10].sort(compare); // [1, 5, 10] [5, 1, 10].sort(compare.reverse); // [10, 5, 1] ``` -------------------------------- ### Map comparison result to values (TypeScript) Source: https://github.com/pallad-ts/compare/blob/master/README.md Demonstrates how to use the `map` method on the comparison result object to transform the result into different values. This can be done using positional arguments or an object with named properties. ```typescript import {compare} from '@pallad/compare'; // using arguments for each value const r1 = compare(1, 5).map('less', 'equal', 'greater') // 'less' type R1 = typeof r1; // 'less' | 'equal' | 'greater' // using object const r2 = compare(1, 5).map({ less: 'less', equal: 'equal', greater: 'greater' }) // 'less' type R2 = typeof r2; // 'less' | 'equal' | 'greater' ``` -------------------------------- ### Compare two values of the same type (TypeScript) Source: https://github.com/pallad-ts/compare/blob/master/README.md Demonstrates the basic usage of the `compare` function from the @pallad/compare library to compare two values. It shows how to check if one value is less than, greater than, or equal to another. ```typescript import {compare} from '@pallad/compare'; compare(1, 2).isLess // true compare(1, 2).isGreater // false compare(1, 2).isEqual // false ``` -------------------------------- ### Map Comparison Results to Booleans in TypeScript Source: https://github.com/pallad-ts/compare/blob/master/README.md Demonstrates mapping comparison results to boolean values using the `compare` function from '@pallad/compare'. It shows both explicit mapping with `.map()` and preferred, more readable methods like `.isEqual` and `.isLessOrEqual`. ```typescript import {compare} from '@pallad/compare'; compare(1, 10).map(false, true, false); // Too explicit ⚠️ compare(1, 10).isEqual // better 👌 compare(1, 10).map(true, true, false); // Too explicit ⚠️ compare(1, 10).isLessOrEqual // better 👌 ``` -------------------------------- ### Basic Value Comparison with @pallad/compare Source: https://context7.com/pallad-ts/compare/llms.txt Demonstrates the core functionality of the `compare` function, showing how it compares two values and returns a `Result` object with boolean properties like `isLess`, `isGreater`, and `isEqual`. It handles basic numeric comparisons and provides utilities for checking relationships between values. ```typescript import { compare } from '@pallad/compare'; // Basic value comparison const result = compare(1, 2); console.log(result.isLess); // true console.log(result.isGreater); // false console.log(result.isEqual); // false console.log(result.isLessOrEqual); // true console.log(result.isNotEqual); // true // Comparing equal values const equalResult = compare(5, 5); console.log(equalResult.isEqual); // true console.log(equalResult.isGreaterOrEqual); // true console.log(equalResult.isLessOrEqual); // true // Greater comparison const greaterResult = compare(10, 3); console.log(greaterResult.isGreater); // true console.log(greaterResult.isGreaterOrEqual); // true ``` -------------------------------- ### Define custom comparator for objects (TypeScript) Source: https://github.com/pallad-ts/compare/blob/master/README.md Illustrates how to define a custom comparator function for objects with a specific interface. This custom comparator can then be used with the `compare` function to sort or compare these objects based on custom logic. ```typescript import {compare} from '@pallad/compare'; interface Option { type: string; value: string; } function comparator(a: Option, b: Option) { return a.type.localeCompare(b.type); } const aValue: Option = { type: '2', value: 'Option 2' }; const bValue: Option = { type: '1', value: 'Option 1' }; compare(aValue, bValue, comparator).isGreater // true compare.reverse(aValue, bValue, comparator).isGreater // false ``` -------------------------------- ### Custom Comparison with Comparable Interface in @pallad/compare Source: https://context7.com/pallad-ts/compare/llms.txt Illustrates how to implement the `Comparable` interface within custom classes to define specific comparison logic. The `compare` function automatically detects and utilizes this interface for objects that implement it, enabling type-safe comparisons for custom value objects like `Money`. ```typescript import { Comparable, Equal, Less, Greater, compare } from '@pallad/compare'; class Money implements Comparable { constructor(readonly value: number, readonly currency: string) {} compare(another: Money) { if (another.currency !== this.currency) { throw new Error('Cannot compare values with different currencies'); } if (another.value === this.value) { return Equal; } else if (this.value < another.value) { return Less; } return Greater; } } const amount100 = new Money(100, 'USD'); const amount200 = new Money(200, 'USD'); const amount100b = new Money(100, 'USD'); // Direct comparison console.log(amount100.compare(amount200)); // Less console.log(amount200.compare(amount100)); // Greater console.log(amount100.compare(amount100b)); // Equal // Using with compare function (auto-detects Comparable) console.log(compare(amount100, amount200).isLess); // true console.log(compare(amount200, amount100).isGreater); // true // Sorting Money objects const amounts = [ new Money(300, 'USD'), new Money(100, 'USD'), new Money(200, 'USD') ]; const sorted = amounts.sort(compare); // [100, 200, 300] ``` -------------------------------- ### Create Reusable Compare Function with Comparator - TypeScript Source: https://context7.com/pallad-ts/compare/llms.txt Creates a reusable comparison function that internally uses a provided comparator. This avoids the need to pass the comparator function every time the comparison function is invoked. It supports direct comparison, reverse sorting, and integration with `Array.sort`. ```typescript import { createCompareWithComparator } from '@pallad/compare'; interface Product { name: string; price: number; } // Create compare function with price comparator const compareByPrice = createCompareWithComparator( (a, b) => a.price - b.price ); const productA: Product = { name: 'Widget', price: 25 }; const productB: Product = { name: 'Gadget', price: 50 }; const productC: Product = { name: 'Tool', price: 25 }; // Use without passing comparator each time console.log(compareByPrice(productA, productB).isLess); // true console.log(compareByPrice(productB, productA).isGreater); // true console.log(compareByPrice(productA, productC).isEqual); // true // Reverse sorting console.log(compareByPrice.reverse(productA, productB).isGreater); // true // Use with Array.sort const products = [productB, productA, productC]; const sortedAsc = [...products].sort(compareByPrice); // by price ascending const sortedDesc = [...products].sort(compareByPrice.reverse); // by price descending ``` -------------------------------- ### Map Comparison Results to Values - TypeScript Source: https://context7.com/pallad-ts/compare/llms.txt The `map` method on comparison results transforms the outcome ('less', 'equal', 'greater') into custom values. It supports mapping using positional arguments or an object with named properties for clarity. This is useful for converting comparison results into user-friendly labels, statuses, or triggering actions. ```typescript import { compare } from '@pallad/compare'; // Map using positional arguments (less, equal, greater) const label1 = compare(1, 5).map('lower', 'same', 'higher'); console.log(label1); // 'lower' const label2 = compare(5, 5).map('lower', 'same', 'higher'); console.log(label2); // 'same' const label3 = compare(10, 5).map('lower', 'same', 'higher'); console.log(label3); // 'higher' // Map using object syntax const status = compare(100, 50).map({ less: 'below target', equal: 'on target', greater: 'above target' }); console.log(status); // 'above target' // Map to different types // const icon = compare(userScore, threshold).map({ // less: '❌', // equal: '✓', // greater: '⭐' // }); // Map to React components or actions // const action = compare(inventory, reorderPoint).map({ // less: () => triggerReorder(), // equal: () => sendWarning(), // greater: () => doNothing() // }); ``` -------------------------------- ### Result Properties for Boolean Comparison Checks - TypeScript Source: https://context7.com/pallad-ts/compare/llms.txt The `Result` object returned by comparison functions provides convenient boolean properties like `isLess`, `isEqual`, and `isGreater` to easily check the comparison outcome. It also offers properties for sorting (`sortResult`, `sortResultReversed`) and reversing the comparison result (`reverse`). Constants like `Less`, `Equal`, and `Greater` are also available for direct use and provide similar boolean helpers and a `valueOf` method for numeric representation (-1, 0, 1). ```typescript import { compare, Less, Equal, Greater } from '@pallad/compare'; const result = compare(5, 10); // All boolean properties available on Result console.log(result.type); // 'less' console.log(result.isLess); // true console.log(result.isEqual); // false console.log(result.isGreater); // false console.log(result.isNotEqual); // true console.log(result.isLessOrEqual); // true console.log(result.isGreaterOrEqual); // false // Sort results for Array.sort console.log(result.sortResult); // -1 console.log(result.sortResultReversed); // 1 // Reverse property returns opposite Result console.log(result.reverse); // Greater console.log(result.reverse.isGreater); // true // Direct use of Result constants console.log(Less.isLess); // true console.log(Equal.isEqual); // true console.log(Greater.isGreater); // true // valueOf for numeric operations console.log(Less.valueOf()); // -1 console.log(Equal.valueOf()); // 0 console.log(Greater.valueOf()); // 1 ``` -------------------------------- ### Comparable Interface Type Guard - TypeScript Source: https://context7.com/pallad-ts/compare/llms.txt The `Comparable.is` type guard allows runtime checking if a given value implements the `Comparable` interface. This is useful for creating generic functions that can conditionally use custom comparison logic defined by the `compare` method or fall back to default comparison methods. It helps ensure type safety when dealing with potentially comparable objects. ```typescript import { Comparable, compare, Less, Equal, Greater } from '@pallad/compare'; class Temperature implements Comparable { constructor(readonly celsius: number) {} compare(another: Temperature) { if (this.celsius === another.celsius) return Equal; return this.celsius < another.celsius ? Less : Greater; } } const temp = new Temperature(25); const plainNumber = 42; const plainObject = { value: 10 }; // Type guard usage console.log(Comparable.is(temp)); // true console.log(Comparable.is(plainNumber)); // false console.log(Comparable.is(plainObject)); // false // Useful for conditional logic function smartCompare(a: T, b: T): string { if (Comparable.is(a) && Comparable.is(b)) { return `Using Comparable: ${a.compare(b).type}`; } return `Using default: ${compare(a, b).type}`; } console.log(smartCompare(temp, new Temperature(30))); // 'Using Comparable: less' console.log(smartCompare(5, 10)); // 'Using default: less' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.