ts-comparator
v1.1.2
Published
A builder for comparator functions, similar in style to Java's Comparator.comparing(), written in and made for Typescript.
Downloads
194
Maintainers
Readme
ReadMe
General
A builder for comparator functions, similar in style to Java's Comparator.comparing(), written in and made for Typescript.
It provides the following functions:
- Simple comparison of arbitrary objects using a key extractor
- Multi-Level comparison using multiple key extractors
- Inversion of the comparison result
- Null/Undefined comparison, priorizing null/undefined values or doing the opposite
Usage
A basic comparator
ComparatorBuilder.comparing<Person>(person => person.name).build();
Multi-Level comparison comparing the persons first name and then the person's last name.
ComparatorBuilder.comparing<Person>(person => person.firstName).thenComparing(person => person.lastName).build();
Null-Tolerant sorting, where non-null values are priorized
ComparatorBuilder.comparing<Person>(person => person.title).definingNullAs(NullMode.LOWEST).build();
Inversed comparison
ComparatorBuilder.comparing<Person>(person => person.lastName).thenComparing(person => person.firstName).inverse().build();
The inverse comparison inverts the final comparison result, not the individual ones.
Null Safety
Because typescript does not (yet) provide a null-safe navigation operator, the nullSafe() exists. With nullSafe(), a key extractor can be secured against null or undefined.
ComparatorBuilder.comparing<Person>(nullSafe(person => person.employer.name)).definingNullAs(NullMode.HIGHEST).build();
The above comparator would place persons without an employer or persons that do not exists (= are null or undefined) at the top of an array sorted with that comparator.