From 98b1350b471cb9f3764181ad9a85f262b527df68 Mon Sep 17 00:00:00 2001 From: Karol Gorski Date: Mon, 28 Jan 2019 20:13:28 +0100 Subject: [PATCH] Update isShallowEqual documentation and unit tests by deep comparison (#13526) * Update isShallowEqual documentation and unit tests by deep comparison * Update packages/is-shallow-equal/README.md Co-Authored-By: Naerriel --- packages/is-shallow-equal/README.md | 18 ++++++++++++++++++ packages/is-shallow-equal/test/index.js | 8 ++++++++ 2 files changed, 26 insertions(+) diff --git a/packages/is-shallow-equal/README.md b/packages/is-shallow-equal/README.md index ac68c2997ac73c..3c53ed3261e445 100644 --- a/packages/is-shallow-equal/README.md +++ b/packages/is-shallow-equal/README.md @@ -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. diff --git a/packages/is-shallow-equal/test/index.js b/packages/is-shallow-equal/test/index.js index ee918194cdad14..49f2526dbdf279 100644 --- a/packages/is-shallow-equal/test/index.js +++ b/packages/is-shallow-equal/test/index.js @@ -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 ];