Skip to content

Ordering

The standard result of comparing two values. An Ordering is -1 when the first value is less than the second, 0 when both values compare as equal, and 1 when the first value is greater than the second. This module also provides helpers for reversing an ordering, matching on the three cases, and combining ordered comparison results with a reducer.

4 exports Added in v2.0.0 Source

Models

Ordering type

Added in v2.0.0 Source

Represents the result of comparing two values.

When to use

Use to model a normalized comparison result that is exactly less than, equal to, or greater than.

Details

- -1 indicates the first value is less than the second - 0 indicates the values are equal - 1 indicates the first value is greater than the second

Signature

type Ordering = -1 | 0 | 1;

Ordering

Reducer

Added in v4.0.0 Source

Reducer for combining Orderings.

When to use

Use to combine multiple comparison results in priority order, such as checking secondary criteria only when earlier criteria compare as equal.

Details

If any of the Orderings is non-zero, the result is the first non-zero Ordering. If all the Orderings are zero, the result is zero.

Gotchas

combineAll stops consuming the iterable as soon as it finds a non-zero Ordering.

Signature

declare const Reducer: Reducer_.Reducer<Ordering>;

Pattern Matching

match

Added in v2.0.0 Source

Matches an Ordering value and returns the branch selected by that ordering.

When to use

Use to branch on the three possible comparison outcomes in one expression.

Signature

declare const match: {
  <A, B, C = B>(options: {
    readonly onEqual: LazyArg<B>;
    readonly onGreaterThan: LazyArg<C>;
    readonly onLessThan: LazyArg<A>;
  }): (self: Ordering) => A | B | C;
  <A, B, C = B>(
    o: Ordering,
    options: {
      readonly onEqual: LazyArg<B>;
      readonly onGreaterThan: LazyArg<C>;
      readonly onLessThan: LazyArg<A>;
    },
  ): A | B | C;
};

Transforming

reverse

Added in v2.0.0 Source

Reverses the ordering of the input Ordering. This is useful for creating descending sort orders from ascending ones.

When to use

Use to flip an ordering result when reversing sort direction or comparison priority.

Signature

declare function reverse(o: Ordering): Ordering;