dittoly
v1.2.0
Published
Fast deep equality for objects, arrays, Maps, Sets, Dates, typed arrays, class instances and circular references, plus diff() with paths for readable test failures. Strict and loose modes, ignoreKeys, customizer. TypeScript, zero dependencies.
Maintainers
Readme
dittoly
Check if two values are deeply equal, and see exactly where they differ.
dittoly compares two values by their contents, not by reference. This is called deep equality. It works with objects, arrays, Map, Set, Date and many other built-in types, and it handles circular references (objects that point back to themselves). Use it in tests, to skip work when data has not changed, or anywhere you would use fast-deep-equal, dequal, lodash.isequal or util.isDeepStrictEqual.
Features
- Compares many types: plain objects, class instances, arrays (also sparse arrays),
Map,Set,Date,RegExp, typed arrays,ArrayBuffer,DataView,Error, boxed primitives,URL,URLSearchParams. - Deep
Mapkeys andSetmembers: object keys and members are matched by content. - Circular references work with no stack overflow.
diff()with paths shows where two values differ, andassertEqual()throws a clear message likeuser.tags[1]: got "b", expected "c".- Two modes: simple defaults, or
strict: trueto match Node'sutil.isDeepStrictEqual. - Options when you need them:
ignoreKeys,ignoreUndefined,customizer,prototype,signedZero,nanEqual,symbols. - Fast: about as fast as
dequal, 3-5x faster thanutil.isDeepStrictEqual, 4-15x faster thanlodash.isequal(see Performance). - Safe: never calls
valueOfortoStringon your objects, never runs getters on their prototypes, and does not hang on unusual inputs. - Small: zero dependencies, about 4.5 KB gzipped.
Installation
npm install dittolypnpm add dittoly
yarn add dittoly
bun add dittolyQuick start
import dittoly, { diff } from 'dittoly'
// CommonJS: const dittoly = require('dittoly')
dittoly({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }) // => true
dittoly(new Set([1, 2]), new Set([2, 1])) // => true
dittoly(new Map([[{ id: 1 }, 'x']]), new Map([[{ id: 1 }, 'x']])) // => true
dittoly(NaN, NaN) // => true
dittoly(0, -0, { strict: true }) // => false
// Skip keys that always change
dittoly({ id: 1, updatedAt: 1 }, { id: 1, updatedAt: 2 }, { ignoreKeys: ['updatedAt'] }) // => true
// Find where two values differ
diff({ user: { tags: ['a', 'b'] } }, { user: { tags: ['a', 'c'] } })
// => [{ kind: 'changed', path: ['user', 'tags', 1], a: 'b', b: 'c' }]Table of contents
- Usage
- API
- How values are compared
- Comparison
- Performance
- Migrating from other packages
- Notes and limitations
- Requirements
- License
Usage
Compare two values
The default export, equal and isEqual are the same function. Use the name you like.
import dittoly, { equal, isEqual } from 'dittoly'
dittoly({ a: 1, b: [1, 2] }, { b: [1, 2], a: 1 }) // => true (key order does not matter)
equal([1, 2], [2, 1]) // => false (array order matters)
isEqual(new Date(0), new Date(0)) // => trueIgnore keys that always change
ignoreKeys skips object keys at any depth. Pass a list of keys, or a function that returns true for keys to skip.
import { equal } from 'dittoly'
equal({ id: 1, meta: { updatedAt: 1 } }, { id: 1, meta: { updatedAt: 2 } }, { ignoreKeys: ['updatedAt'] })
// => true
equal({ _rev: 'a', name: 'Ann' }, { _rev: 'b', name: 'Ann' }, { ignoreKeys: (key) => key.startsWith('_') })
// => trueTreat undefined properties as missing
By default, { a: undefined } and {} are different. With ignoreUndefined: true, a property set to undefined counts as missing.
import { equal } from 'dittoly'
equal({ a: 1, b: undefined }, { a: 1 }) // => false
equal({ a: 1, b: undefined }, { a: 1 }, { ignoreUndefined: true }) // => trueCompare class instances by their properties
By default, the prototype (the class an object was made from) must match. Set prototype: false to compare class instances by their properties only.
import { equal } from 'dittoly'
class Point {
constructor(x, y) {
this.x = x
this.y = y
}
}
equal(new Point(1, 2), { x: 1, y: 2 }) // => false
equal(new Point(1, 2), { x: 1, y: 2 }, { prototype: false }) // => trueUse your own rule for some values
A customizer is a function that runs before the built-in rules. Return true or false to decide, or undefined to let dittoly continue.
import { equal } from 'dittoly'
// Compare strings without case
equal({ name: 'ANN' }, { name: 'ann' }, {
customizer: (a, b) => (typeof a === 'string' && typeof b === 'string' ? a.toLowerCase() === b.toLowerCase() : undefined),
}) // => true
// Allow small number errors
equal({ total: 0.1 + 0.2 }, { total: 0.3 }, {
customizer: (a, b) => (typeof a === 'number' && typeof b === 'number' ? Math.abs(a - b) < 1e-9 : undefined),
}) // => trueReuse the same options
createEqual() builds a comparator with the options built in. Use it when you call with the same customizer or ignoreKeys many times. Options made only of booleans are cached for you, so you do not need createEqual for those.
import { createEqual } from 'dittoly'
const sameRecord = createEqual({ ignoreKeys: ['updatedAt', '_rev'] })
const rows = [{ id: 1, updatedAt: 5 }, { id: 2, _rev: 'x' }]
const previous = [{ id: 1, updatedAt: 9 }, { id: 3 }]
rows.filter((row, i) => !sameRecord(row, previous[i])) // => [{ id: 2, _rev: 'x' }]Find where two values differ
diff() returns a list of differences. Each one has a kind ('changed', 'added' or 'removed') and a path (the keys and indexes that lead to the value). formatPath() turns a path into a readable string.
import { diff, formatPath } from 'dittoly'
const changes = diff(
{ user: { name: 'Ann', tags: ['x', 'y'], age: 30 } },
{ user: { name: 'Ann', tags: ['x', 'z', 'w'], email: '[email protected]' } },
)
// => [
// { kind: 'changed', path: ['user', 'tags', 1], a: 'y', b: 'z' },
// { kind: 'added', path: ['user', 'tags', 2], b: 'w' },
// { kind: 'removed', path: ['user', 'age'], a: 30 },
// { kind: 'added', path: ['user', 'email'], b: '[email protected]' },
// ]
changes.map((d) => formatPath(d.path))
// => ['user.tags[1]', 'user.tags[2]', 'user.age', 'user.email']diff(a, b, options) returns [] exactly when equal(a, b, options) is true.
Get a clear error in tests
assertEqual() throws a NotEqualError that lists every difference. The error also has diffs, actual and expected properties.
import { assertEqual } from 'dittoly'
try {
assertEqual({ user: { name: 'Ann', age: 3 } }, { user: { name: 'Bob' } })
} catch (error) {
console.log(error.message)
// Expected values to be deeply equal (2 differences):
// user.name: got "Ann", expected "Bob"
// user.age: got 3, expected (missing)
}In TypeScript, actual has the type of expected after the call:
import { assertEqual } from 'dittoly'
const body: unknown = await response.json()
assertEqual(body, { ok: true })
body.ok // TypeScript now knows this is a booleanMatch Node's util.isDeepStrictEqual
The default mode compares what most people mean by "the same data". strict: true follows Node's util.isDeepStrictEqual.
| Case | Default | strict: true |
|---|---|---|
| NaN vs NaN | Equal | Equal |
| +0 vs -0 | Equal | Different |
| { a: undefined } vs {} | Different (use ignoreUndefined) | Different |
| [, 1] (empty slot) vs [undefined, 1] | Equal | Different |
| {} vs Object.create(null) vs an object from another realm (iframe or vm context) | Equal | Different |
| new Point(1, 2) vs { x: 1, y: 2 } | Different (use prototype: false) | Different |
| Symbol keys | Ignored | Compared |
| Extra properties on arrays, Dates, Maps, Sets, RegExps | Ignored | Compared |
| RegExp lastIndex | Ignored | Compared |
You can change each row with an option. For example, { strict: true, signedZero: false } is strict mode where 0 equals -0.
import { equal } from 'dittoly'
equal([, 1], [undefined, 1]) // => true
equal([, 1], [undefined, 1], { strict: true }) // => false
equal(0, -0, { strict: true, signedZero: false }) // => trueAPI
dittoly(a, b, options?)
function dittoly(a: unknown, b: unknown, options?: EqualOptions): booleanThe default export. Returns true if a and b are deeply equal. All named exports are also attached to it: dittoly.equal, dittoly.isEqual, dittoly.createEqual, dittoly.diff, dittoly.assertEqual, dittoly.formatPath and dittoly.NotEqualError. In CommonJS, require('dittoly') returns this function.
equal(a, b, options?) and isEqual(a, b, options?)
function equal(a: unknown, b: unknown, options?: EqualOptions): boolean
const isEqual: typeof equalThe same as dittoly, as named exports. isEqual is an alias for code coming from lodash.
| Option | Type | Default | Description |
|---|---|---|---|
| strict | boolean | false | Match util.isDeepStrictEqual (see the table above). Sets the defaults of signedZero, symbols and prototype. |
| prototype | boolean | true | Compare prototypes. Outside strict mode, plain objects, Object.create(null) objects and objects from other realms count as the same. false compares class instances by properties only (arrays, Maps, Dates and so on still only equal their own kind). |
| signedZero | boolean | same as strict | +0 and -0 are different (also inside float typed arrays). |
| nanEqual | boolean | true | NaN equals NaN. |
| symbols | boolean | same as strict | Compare own enumerable symbol keys. |
| ignoreUndefined | boolean | false | A property set to undefined counts as missing: { a: undefined } equals {}. Array elements are not affected. |
| ignoreKeys | PropertyKey[] \| ((key, object) => boolean) | none | Object keys to skip at any depth. A function returns true for keys to skip. Not used for Map keys or array indexes. |
| customizer | (a, b) => boolean \| undefined | none | Runs before the built-in rules. Return a boolean to decide, or undefined to continue. |
The customizer is called for every pair of values that is compared: the root values, properties, array elements, Map values, and Set members or Map keys that are not found by identity. It is not called for typed array elements.
A TypeError is thrown if options is not an object, ignoreKeys is not a list or function, or customizer is not a function.
createEqual(options?)
function createEqual(options?: EqualOptions): Comparator
type Comparator = (a: unknown, b: unknown) => booleanReturns a comparator with the options built in. It is faster than passing the same customizer or ignoreKeys on every call. Takes the same options as equal.
diff(a, b, options?)
function diff(a: unknown, b: unknown, options?: EqualOptions): Difference[]
type Difference =
| { kind: 'changed'; path: Path; a: unknown; b: unknown }
| { kind: 'removed'; path: Path; a: unknown } // only in a
| { kind: 'added'; path: Path; b: unknown } // only in b
type Path = unknown[] // object keys, array indexes (numbers), Map keys; [] is the rootLists the differences between a and b. Returns [] exactly when equal(a, b, options) is true. Takes the same options as equal.
- Objects, arrays and Maps are walked key by key. Map keys appear in the path as they are.
- Anything else that differs (a primitive,
Date,Set,Errorand so on) is one'changed'entry at its path. - Arrays are compared index by index. An inserted item is not detected as a move.
- In strict mode, empty array slots show up as
'added'or'removed'.
assertEqual(actual, expected, options?)
function assertEqual<T>(actual: unknown, expected: T, options?: AssertOptions): asserts actual is T
interface AssertOptions extends EqualOptions {
message?: string
}Throws a NotEqualError unless equal(actual, expected, options) is true. The message lists up to 20 differences. In TypeScript, actual has the type of expected after the call.
| Option | Type | Default | Description |
|---|---|---|---|
| message | string | generated | Use this message instead of the generated list of differences. |
| (all equal options) | | | See equal(). |
formatPath(path)
function formatPath(path: readonly unknown[]): stringTurns a path into a readable string.
import { formatPath } from 'dittoly'
formatPath(['user', 'tags', 1]) // => 'user.tags[1]'
formatPath(['a-b']) // => '["a-b"]'
formatPath([]) // => ''NotEqualError
class NotEqualError extends Error {
name: string // 'NotEqualError'
readonly diffs: Difference[]
readonly actual: unknown
readonly expected: unknown
constructor(actual: unknown, expected: unknown, diffs: Difference[], message?: string)
}Thrown by assertEqual(). diffs holds the differences as returned by diff(actual, expected).
Types
These TypeScript types are exported: EqualOptions, AssertOptions, Customizer, IgnoreKeys, Comparator, Difference, Path, Dittoly.
How values are compared
- Primitives:
===, plusNaNequalsNaN. Functions and symbols are compared by identity (same reference). - Objects: own enumerable string keys, in any order. Symbol keys too with
symbolsorstrict. Getters on prototypes are never called, and non-enumerable properties are ignored. - Arrays: same length, same elements in the same order.
- Map: same size, same keys and values in any order. Object keys are matched by content.
- Set: same size, same members in any order. Object members are matched by content.
- Date: same time. Two invalid dates are equal.
- RegExp: same source and flags.
- Typed arrays: same type, length and elements.
- ArrayBuffer, SharedArrayBuffer, DataView: same bytes.
- Error: same
name,message,cause,errors(forAggregateError) and own enumerable properties. The stack is ignored. - Boxed primitives (
new Number(1),Object(1n)): same type and value. - URL: same
href. URLSearchParams: same string. Temporal objects: same string form. - Promise, WeakMap, WeakSet, WeakRef, Blob, streams: equal only if they are the same object, because their contents cannot be read synchronously.
- Circular references: two structures are equal if they unfold into the same (endless) tree. So an object that points to itself equals a two-step loop with the same data.
Comparison
These are the results each package actually returns (fast-deep-equal 3.1.3, dequal 2.0.3, lodash.isequal 4.5.0, Node 20.14).
| | fast-deep-equal | fast-deep-equal/es6 | dequal | lodash.isequal | util.isDeepStrictEqual | dittoly |
|---|---|---|---|---|---|---|
| Circular references | No (stack overflow) | No (stack overflow) | No (stack overflow) | Yes | Yes | Yes |
| Map / Set | No (any two Maps are equal) | Yes | Yes | Yes | Yes | Yes |
| Object keys in a Map / objects in a Set | No | No (by reference only) | Yes | Yes | Yes | Yes |
| ArrayBuffer / DataView | No (always equal) | No (always equal; hangs on DataView) | Yes | Yes | Yes | Yes |
| Tells new Error('a') and new Error('b') apart | Yes | Yes | No | Yes | Yes | Yes |
| Tells new Number(1) and new Number(2) apart | Yes | Yes | No | Yes | Yes | Yes |
| Tells two different URLs apart | Yes | Yes | Yes | Yes | No | Yes |
| Tells two different Promises / WeakMaps apart | No | No | No | Yes | No | Yes |
| Tells { valueOf: () => 1, a: 1 } and { valueOf: () => 1, a: 2 } apart | No (trusts valueOf) | No | Yes | Yes | Yes | Yes |
| +0 vs -0 | Equal | Equal | Equal | Equal | Different | Your choice (strict / signedZero) |
| Sparse [, 1] vs [undefined, 1] | Equal | Equal | Equal | Equal | Different | Your choice (strict) |
| Symbol keys | Ignored | Ignored | Ignored | Compared | Compared | Your choice (strict / symbols) |
| Ignore keys / customizer | No | No | No | Customizer only (isEqualWith) | No | Yes, both |
| Diff with paths | No | No | No | No | No | Yes (diff()) |
| Runs in browsers | Yes | Yes | Yes | Yes | No (Node only) | Yes |
| TypeScript types | Yes | Yes | Yes | Through @types/lodash.isequal | Yes | Yes |
lodash.isequal is deprecated on npm. deep-equal has 18 runtime dependencies; dittoly has none.
Performance
Operations per second on Node 20.14 (higher is better). These numbers come from one laptop, so treat them as a rough guide. The benchmark script is not part of the package.
| | dittoly | dittoly strict | util.isDeepStrictEqual | fast-deep-equal | dequal | lodash.isequal |
|---|---|---|---|---|---|---|
| Small nested object, equal | 1.9M | 620K | 390K | 1.6M | 1.7M | 460K |
| Small nested object, differs deep inside | 1.8M | 740K | 420K | 5.5M | 2.0M | 460K |
| Array of 1000 small objects | 14.6K | 5.9K | 4.3K | 10.6K | 13.1K | 2.4K |
| Object with a Map, a Set and a Date | 3.3M | 1.2M | 690K | (no Map support) | 4.1M | 210K |
In strict mode, dittoly does the same work as util.isDeepStrictEqual and is about 1.5x faster.
Circular reference checks cost nothing on normal data. dittoly only starts tracking visited objects when a comparison goes more than 100 levels deep.
Migrating from other packages
From fast-deep-equal or dequal
// Before
import equal from 'fast-deep-equal' // or: import { dequal as equal } from 'dequal'
// After
import { equal } from 'dittoly'
equal(a, b)You get the same answers for JSON data. This was checked on 200,000 random values against both packages and lodash.isequal. dittoly also compares Maps, Sets, buffers, Errors and circular references correctly.
Like both packages, dittoly compares prototypes, so new Point(1, 2) does not equal { x: 1, y: 2 }. Pass { prototype: false } to allow it.
From lodash.isequal
// Before
import { isEqual, isEqualWith } from 'lodash'
isEqual(a, b)
isEqualWith(a, b, fn)
// After
import { isEqual } from 'dittoly'
isEqual(a, b)
isEqual(a, b, { customizer: (x, y) => fn(x, y) })The dittoly customizer gets the two values only. lodash compares symbol keys, so add { symbols: true } to do the same.
From util.isDeepStrictEqual
// Before
import { isDeepStrictEqual } from 'node:util'
isDeepStrictEqual(a, b)
// After
import { equal } from 'dittoly'
equal(a, b, { strict: true })The test suite checks that the two agree on thousands of random values. One difference: dittoly says two different URLs, Promises or WeakMaps are not equal.
From Jest or Vitest toEqual
To compare like toEqual (ignore class types and undefined properties), use these options:
// Before
expect(actual).toEqual(expected)
// After
import { assertEqual } from 'dittoly'
assertEqual(actual, expected, { prototype: false, ignoreUndefined: true })Notes and limitations
- Private class fields (
#x) and closures cannot be read, so instances that differ only there compare as equal. Use acustomizerfor such classes. - Very deep nesting (thousands of levels) can overflow the call stack, as with the other libraries.
customizerandignoreKeysfunctions may run more than once for the same values on very deep or circular data.diff()compares arrays index by index, so an inserted item shows up as several changes, not as a move.assertEqual()shows up to 20 differences in its message. The full list is inerror.diffs.
Requirements
- Node.js 20 or later. Also works in Bun, Deno and browsers.
- ESM and CommonJS.
- TypeScript types included.
- Zero dependencies.
License
MIT
