castComparator
Cast a value into a comparator function
230 bytes
Usage
Create a comparator function which can be passed into Array.prototype.sort
. It accepts either a property name or a mapping function. Optionally, you can pass a custom compare function (e.g. for localeCompare
use cases).
The first argument of castComparator
is called the mapping
. This can be either:
- Function: If
mapping
is a function, it maps the input values to a comparable value. - Property Name: If
mapping
is a property name, it maps the input values to a property of the input values with a comparable value.
Compare Function
Optionally, you can pass a custom compare
function that receives the mapped values and returns a number. If not provided, values are compared with the <
and >
built-in operators.
A positive number means the “right value” is greater than the “left value”, a negative number means the “left value” is greater than the “right value”, and 0 means both values are equal.