ts-comparators
This is a comparators package written in TypeScript
Usage
Reversing
Reversing a comparator is as simple as calling its reverse
method. The reverse
method will return a new ChainableComparator
that does the same thing as the original one in the reverse order.
;;values.sortcomparator.comparevalue1, value2;// values = [3, 2, 1]
Chaining
Chaining comparators is what makes this package really powerful. You can combine multiple comparators to create subsorts in an efficient manner.
; .reverse .thennew ValueComparatorobj.prop2, new StringComparator;values.sortcomparator.comparevalue1, value2;//values = [,// { prop1: 2, prop2: 'hello' },// { prop1: 1, prop2: 'baseball' },// { prop1: 1, prop2: 'xylophone' }//];
Comparators
ChainableComparator
The ChainableComparator
is an abstract class that adds the ability to do chaining and reversing of the other comparators.
BasicComparator
The BasicComparator
is the simplest of all the comparators and doesn't do anything special except that it can be used internally by other comparators and possesses the ChainableComparator
functionality.
;;values.sortcomparator.comparevalue1, value2;// values = [1, 2, 3]
StringComparator
The StringComparator
is basically a wrapper around Intl.collator
for it to work with the rest of the comparators in this package.
;;values.sortcomparator.comparevalue1, value2;// values = ['one', 'three', 'two']
PropertyComparator
The PropertyComparator
is used to compare objects by a specific property in them. It takes the name of the property to use for the comparison as the first parameter and comparator to perform the comparison as the second parameter.
;;values.sortcomparator.comparevalue1, value2;// values = [{prop: 1}, {prop: 2}, {prop: 3}]
ValueComparator
The ValueComparator
is one of the most powerful comparators because it allows you to transform the value prior to comparison or it can simply by used to pluck values out of an object. It takes function that transforms the value to use for the comparison as the first parameter and comparator to perform the comparison as the second parameter.
;;values.sortcomparator.comparevalue1, value2;// values = [{prop: 1}, {prop: 2}, {prop: 3}]
CustomComparator
The CustomComparator
is a utility comparator to convert a regular compare function in to a ChainableComparator
.
;;values.sortcomparator.comparevalue1, value2;// values = [1, 2, 3]