ts-comparator
TypeScript icon, indicating that this package has built-in type declarations

1.1.2 • Public • Published

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.

Package Sidebar

Install

npm i ts-comparator

Weekly Downloads

84

Version

1.1.2

License

ISC

Unpacked Size

77.9 kB

Total Files

21

Last publish

Collaborators

  • nthilmont