Creates a comparator function for string-based sorting with locale-aware comparison.

Generates a comparator that extracts string values from objects and performs lexicographic comparison using locale-sensitive string comparison. Supports both single strings and arrays of strings for multi-field sorting scenarios.

When comparing arrays, performs lexicographic ordering: compares the first elements, then the second elements if the first are equal, and so on. This enables complex sorting like "sort by last name, then by first name".

  interface User {
id: string;
firstName: string;
lastName: string;
email: string;
status: 'active' | 'inactive';
}

const users: User[] = [
{ id: '1', firstName: 'John', lastName: 'Doe', email: 'john@example.com', status: 'active' },
{ id: '2', firstName: 'Jane', lastName: 'Doe', email: 'jane@example.com', status: 'inactive' },
{ id: '3', firstName: 'Bob', lastName: 'Smith', email: 'bob@example.com', status: 'active' }
];

// Single field sorting
users.sort(GaffComparator.strings(user => user.lastName));
// Result: Doe, Doe, Smith

// Multi-field sorting: last name, then first name
users.sort(GaffComparator.strings(user => [user.lastName, user.firstName]));
// Result: Doe Jane, Doe John, Smith Bob

// Status-based sorting
users.sort(GaffComparator.strings(user => user.status));
// Result: active users first, then inactive

// Complex multi-field: status, then last name, then first name
users.sort(GaffComparator.strings(user => [user.status, user.lastName, user.firstName]));

// Integration with API sorting validation
await TestValidator.sort("user name sorting")(
(sortFields) => userApi.getUsers({ sort: sortFields })
)("lastName", "firstName")(
GaffComparator.strings(user => [user.lastName, user.firstName])
)("+");
  • Type Parameters

    • T

      The type of objects being compared

    Parameters

    • getter: (input: T) => string | string[]

      Function that extracts string value(s) from input objects

    Returns (x: T, y: T) => number

    A comparator function suitable for Array.sort()