Skip to content

Commit

Permalink
Update isShallowEqual documentation and unit tests by deep comparison (
Browse files Browse the repository at this point in the history
…#13526)

* Update isShallowEqual documentation and unit tests by deep comparison

* Update packages/is-shallow-equal/README.md

Co-Authored-By: Naerriel <[email protected]>
  • Loading branch information
Naerriel authored and aduth committed Jan 28, 2019
1 parent 0148965 commit 98b1350
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
18 changes: 18 additions & 0 deletions packages/is-shallow-equal/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,24 @@ import { isShallowEqualArrays } from '@wordpress/is-shallow-equal';
import { isShallowEqualObjects } from '@wordpress/is-shallow-equal';
```

Shallow comparison differs from deep comparison by the fact that it compares members from each as being strictly equal to the other, meaning that arrays and objects will be compared by their _references_, not by their values (see also [_Object Equality in JavaScript_.](http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html)) In situations where nested objects must be compared by value, consider using [Lodash's `isEqual`](https://lodash.com/docs/4.17.11#isEqual) instead.

```js
import isShallowEqual from '@wordpress/is-shallow-equal';
import { isEqual } from 'lodash'; // deep comparison

let object = { a: 1 };

isShallowEqual( [ { a: 1 } ], [ { a: 1 } ] );
// ⇒ false

isEqual( [ { a: 1 } ], [ { a: 1 } ] );
// ⇒ true

isShallowEqual( [ object ], [ object ] );
// ⇒ true
```

## Rationale

Shallow equality utilities are already a dime a dozen. Since these operations are often at the core of critical hot code paths, the WordPress contributors had specific requirements that were found to only be partially satisfied by existing solutions.
Expand Down
8 changes: 8 additions & 0 deletions packages/is-shallow-equal/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ describe( 'isShallowEqual', () => {
expect( isShallowEqual( b, a ) ).toBe( true );
} );

it( 'returns false on object deep-but-referentially-unequal values', () => {
const a = { foo: {} };
const b = { foo: {} };

expect( isShallowEqual( a, b ) ).toBe( false );
expect( isShallowEqual( b, a ) ).toBe( false );
} );

it( 'returns false if a array has more keys than b', () => {
const a = [ 1, 2 ];
const b = [ 1 ];
Expand Down

0 comments on commit 98b1350

Please sign in to comment.