1.0.2 • Published 4 years ago

@asmartbear/pojo-compare v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
4 years ago

POJO Compare

Extremely fast deep-comparison function (both "equal" and "greater/equal/lesser") for POJOs that are compatible with JSON-encoding, meaning for types matching this Typescript definition:

type POJO = null|boolean|number|string|Array<POJO>|{ [field:string]: POJO };

Uses:

  • Like "Deep Equal," but additional option for total ordering.
  • In Array#sort() to sort POJOs quickly.

Features:

  • Fast: Faster than other npm libraries for deep-equals (see below), due to only caring about POJOs.
  • Small: No dependencies, extremely small amount of code.
  • Typescript: Written in Typescript, but distributed as regular Javascript, and includes Typescript declarations.

Usage

Use through npm, or get the source from Github.

equal()

import { equal as eq } from '@asmartbear/pojo-compare';

console.log(eq(null,null));            // -> true
console.log(eq(null,undefined));       // -> false
console.log(eq(123,"123"));            // -> false   (type-specific!)
console.log(eq([1,"2"],[1,"2"]]));     // -> true
console.log(eq({a:1,b:2}, {b:2,a:1})); // -> true

compare()

Returns -1 if lesser, 1 if greater, or 0 if equal. If you supply non-POJO objects, the results are undefined.

import { compare as cmp } from '@asmartbear/pojo-compare';

console.log(cmp(null,null));  // -> 0
console.log(cmp(null,undefined)); // -> 1  (null > undefined as a convention)
console.log(cmp(123,321));    // -> -1
console.log(cmp(123,"1"));    // -> -1     (numbers always less than strings)
console.log(cmp("21","1"));   // -> 1      (strings compared as strings)
console.log(cmp([],[]]));     // -> 0
console.log(cmp([],{}));      // -> -1
console.log(cmp([1,5,5],[99,5,5])); // -> -1   (arrays compare in order)
console.log(cmp(
    {a: 1, b: 2},
    {a: 2, b: 1}
)); // -> -1   (maps compare keys in their sorted order)
console.log(cmp(
    {a: 2},
    {b: 1}
)); // -> -1   (maps keys come first; here a < b)

Benchmarks

The benchmarks are included in the project if you want to run them youself, or please contribute new ones!

This equal is the fastest; compare is slower due to fewer opportunities for short-circuiting the answer.

pojo-compare x 11,120 ops/sec ±1.43% (91 runs sampled)
pojo-equal x 18,642 ops/sec ±0.81% (95 runs sampled)
qcompare x 17,547 ops/sec ±1.34% (89 runs sampled)
fast-deep-equal x 15,459 ops/sec ±1.38% (86 runs sampled)
fast-equals x 13,019 ops/sec ±1.43% (90 runs sampled)
nano-equal x 11,296 ops/sec ±1.31% (87 runs sampled)
deep-equal x 11.37 ops/sec ±1.79% (33 runs sampled)
deep-eql x 4,550 ops/sec ±1.03% (91 runs sampled)
Fastest is pojo-equal