1.1.1 • Published 1 year ago
sorting-lib v1.1.1
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
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.
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:
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.
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:
// Inverts the comparison
comparatorBuilder<SomeType>()
.add(someComparator)
.invert()
.build()
Combining a dynamic array of comparators
declare const arrayOfComparators: Comparator<SomeType>[];
const combinedComparator: Comparator<SomeType> =
chainComparators(arrayOfComparators);