Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update isShallowEqual documentation and unit tests by deep comparison #13526

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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