Options
All
  • Public
  • Public/Protected
  • All
Menu

@thi.ng/compare

compare

npm versionnpm downloads Twitter Follow

This project is part of the @thi.ng/umbrella monorepo.

About

Comparators with optional support for types implementing the @thi.ng/api ICompare interface.

Since v1.2.0 additional higher-order comparators are included, e.g. to reverse the ordering of an existing comparator and allow hierarchical sorting by multiple keys/dimensions, each with their own optional comparator. See examples below.

Status

STABLE - used in production

Installation

yarn add @thi.ng/compare
// ES module
<script type="module" src="https://unpkg.com/@thi.ng/compare?module" crossorigin></script>

// UMD
<script src="https://unpkg.com/@thi.ng/compare/lib/index.umd.js" crossorigin></script>

Package sizes (gzipped, pre-treeshake): ESM: 396 bytes / CJS: 471 bytes / UMD: 519 bytes

Dependencies

Usage examples

Several demos in this repo's /examples directory are using this package.

A selection:

ScreenshotDescriptionLive demoSource
Full umbrella repo doc string search w/ paginated resultsDemoSource
Triple store query results & sortable tableDemoSource

API

Generated API docs

ICompare support

import { ICompare } from "@thi.ng/api";
import { compare } from "@thi.ng/compare";

class Foo implements ICompare<Foo> {

    x: number;

    constructor(x: number) {
        this.x = x;
    }

    compare(o: Foo) {
        return compare(this.x, o.x);
    }
}

compare(new Foo(1), new Foo(2));
// -1

Cluster sort w/ multiple sort keys

Key-based object comparison is supported for 1 - 4 keys / dimensions.

import * as cmp from "@thi.ng/compare";

const src = [
    { id: "charlie", age: 66 },
    { id: "bart", age: 42 },
    { id: "alice", age: 23 },
    { id: "dora", age: 11 },
];

// cluster sort by id -> age (default comparators)
[...src].sort(cmp.compareByKeys2("id", "age"));
// [
//   { id: 'alice', age: 23 },
//   { id: 'bart', age: 42 },
//   { id: 'charlie', age: 66 },
//   { id: 'dora', age: 11 }
// ]

// cluster sort by age -> id (default comparators)
[...src].sort(cmp.compareByKeys2("age", "id"));
// [
//   { id: 'dora', age: 11 },
//   { id: 'alice', age: 23 },
//   { id: 'bart', age: 42 },
//   { id: 'charlie', age: 66 }
// ]

// cluster sort by age -> id
// (custom comparator for `age` key)
[...src].sort(cmp.compareByKeys2("age", "id", cmp.compareNumDesc));
// [
//   { id: 'charlie', age: 66 },
//   { id: 'bart', age: 42 },
//   { id: 'alice', age: 23 },
//   { id: 'dora', age: 11 }
// ]

// using `reverse()` comparator for `id`
[...src].sort(cmp.compareByKeys2("age", "id", cmp.compare, cmp.reverse(cmp.compare)));
// [
//   { id: 'dora', age: 11 },
//   { id: 'alice', age: 23 },
//   { id: 'bart', age: 42 },
//   { id: 'charlie', age: 66 }
// ]

Authors

Karsten Schmidt

License

© 2016 - 2020 Karsten Schmidt // Apache Software License 2.0

Generated using TypeDoc