The type of objects being compared
Function that extracts number value(s) from input objects
A comparator function suitable for Array.sort()
interface Product {
id: string;
name: string;
price: number;
rating: number;
stock: number;
categoryId: number;
salesCount: number;
}
const products: Product[] = [
{ id: '1', name: 'Laptop', price: 999.99, rating: 4.5, stock: 15, categoryId: 1, salesCount: 150 },
{ id: '2', name: 'Mouse', price: 29.99, rating: 4.2, stock: 50, categoryId: 1, salesCount: 300 },
{ id: '3', name: 'Keyboard', price: 79.99, rating: 4.8, stock: 25, categoryId: 1, salesCount: 200 }
];
// Sort by price (ascending)
products.sort(GaffComparator.numbers(product => product.price));
// Result: Mouse ($29.99), Keyboard ($79.99), Laptop ($999.99)
// Sort by rating (descending requires negation)
products.sort(GaffComparator.numbers(product => -product.rating));
// Result: Keyboard (4.8), Laptop (4.5), Mouse (4.2)
// Multi-field: category, then price
products.sort(GaffComparator.numbers(product => [product.categoryId, product.price]));
// Complex business logic: popularity (sales) then rating
products.sort(GaffComparator.numbers(product => [-product.salesCount, -product.rating]));
// Negative values for descending order
// Sort by inventory priority: low stock first, then by sales
products.sort(GaffComparator.numbers(product => [product.stock, -product.salesCount]));
// Validate API numerical sorting with TestValidator
const priceValidator = TestValidator.sort("product price sorting",
(sortFields) => productApi.getProducts({ sort: sortFields })
)("price")(
GaffComparator.numbers(product => product.price)
);
await priceValidator("+"); // test ascending order
await priceValidator("-"); // test descending order
// Test multi-criteria sorting
const sortByBusinessValue = GaffComparator.numbers(product => [
-product.salesCount, // High sales first
-product.rating, // High rating first
product.price // Low price first (for tie-breaking)
]);
Creates a comparator function for numerical sorting with multi-value support.
Generates a comparator that extracts numerical values from objects and performs mathematical comparison. Supports both single numbers and arrays of numbers for complex numerical sorting scenarios like sorting by price then by rating.
When comparing arrays, performs lexicographic numerical ordering: compares the first numbers, then the second numbers if the first are equal, and so on. This enables sophisticated sorting like "sort by price ascending, then by rating descending".