sorting-lib
Version:
A library that makes sorting easier by introducing `Comparator`
88 lines (63 loc) • 1.92 kB
Markdown
# Sorting Lib
Javascript has no built-in ways to easily handle the comparison between objects.
This is why this library exists, it provides an intuitive API to create comparators.
Install by running:
```
npm i sorting-lib
```
The project is maintained on [Gitlab](https://gitlab.com/louis-boucquet/sorting-lib)
## Comparing
With you `comparing` function you can select a key to compare by.
Selecting a key happens by either a dot-seperated string or a lambda function.
```ts
const array = [
{ value: 1, object: { subValue: 1 } },
{ value: 2, object: { subValue: 2 } },
];
array.sort(comparing(item => item.value));
array.sort(comparing(item => item.object.subValue));
array.sort(comparing('value'));
array.sort(comparing('object.subValue'));
```
## Handling Nil
You can choose Nil (`null | undefined`) values to be either a maximum or a minimum:
```ts
const array = [
{ value: 1 },
{},
];
array.sort(comparing(item => item.value), NilAs.Max);
```
## Comparator builder
For more complex sorting needs you can combine multiple "simple" comparators into one.
An example where this might be useful is sorting names.
```ts
type Person = { firstName: string, lastName: string }
const fullNames = [
{ firstName: 'a', lastName: 'b' },
{ firstName: 'a', lastName: 'c' },
];
fullNames.sort(
// Compares `firstName` first, then falls back to `lastName`
comparatorBuilder<Person>()
.add(comparing('firstName'))
.add(comparing('lastName'))
.build(),
);
```
> Note: as of now typescript's type inference is not strong enough to infer the `Person` type
## Invert
Inverting a comparison:
```ts
// Inverts the comparison
comparatorBuilder<SomeType>()
.add(someComparator)
.invert()
.build()
```
## Combining a dynamic array of comparators
```ts
declare const arrayOfComparators: Comparator<SomeType>[];
const combinedComparator: Comparator<SomeType> =
chainComparators(arrayOfComparators);
```