Skip to content

Instantly share code, notes, and snippets.

@kenny-chow-my
Created March 26, 2018 02:44
Show Gist options
  • Save kenny-chow-my/e6200b2c0ba501450bb7ba93dc5ca8cc to your computer and use it in GitHub Desktop.
Save kenny-chow-my/e6200b2c0ba501450bb7ba93dc5ca8cc to your computer and use it in GitHub Desktop.
shallow equals
diff --git a/devportal/src/js/utils/shallowcompare.js b/devportal/src/js/utils/shallowcompare.js
new file mode 100644
index 00000000..1409ebe1
--- /dev/null
+++ b/devportal/src/js/utils/shallowcompare.js
@@ -0,0 +1,23 @@
+/**
+ * Shallow compare, inspired from
+ * https://github.com/developit/preact-compat/blob/7c5de00e7c85e2ffd011bf3af02899b63f699d3a/src/index.js#L349
+ * @param {*} src object to compare
+ * @param {*} target object to compare
+ * @returns true if they are shallow equals, false otherwise.
+ */
+export function shallowEquals (a, b) {
+ if(!a && a === b){
+ return true;
+ }
+
+ for (const [key, value] of Object.entries(a)) {
+ if (!(key in b)) {
+ return false;
+ }
+ if(value !== b[key]){
+ return false;
+ }
+ }
+
+ return true;
+}
diff --git a/devportal/test/utils/shallowcompare_test.js b/devportal/test/utils/shallowcompare_test.js
new file mode 100644
index 00000000..23c9fafd
--- /dev/null
+++ b/devportal/test/utils/shallowcompare_test.js
@@ -0,0 +1,39 @@
+import { expect } from 'chai';
+import { shallowEquals } from 'DEVPORTAL/utils/shallowcompare';
+
+describe('shallow compare utilities', function () {
+
+ it('shallowEquals should shallowly compare 2 objects', function () {
+ const c1 = null;
+ const c2 = null;
+ const c3 = {child1: 1, child2: 2};
+ const c4 = {child1: 1, child2: 2};
+ const c5 = [1, 'a', c1, c3];
+ const c6 = [1, 'a', c1, c3];
+ const c7 = [1, 'a', null, c3];
+ const c8 = [1, 'a', null, c4];
+ const c9 = {children: c3};
+ const c10 = {children: c4};
+
+ expect(shallowEquals(c1, c2)).to.equal(true);
+ expect(shallowEquals(c3, c4)).to.equal(true);
+ expect(shallowEquals(c5, c6)).to.equal(true);
+
+ //null is equal no matter declared or assigned
+ expect(shallowEquals(c5, c7)).to.equal(true);
+
+ //direct child differs
+ expect(shallowEquals(c7, c8)).to.equal(false);
+ expect(shallowEquals(c5, c8)).to.equal(false);
+ expect(shallowEquals(c9, c10)).to.equal(false);
+
+ //child objects are not compared in shallow compare
+ c5[3].child1 = 3; //c3
+ expect(shallowEquals(c3, c4)).to.equal(false);
+ expect(shallowEquals(c5, c7)).to.equal(true);
+
+ c10.children = c3;
+ expect(shallowEquals(c9, c10)).to.equal(true);
+ expect(c9.children.child1).to.equal(3);
+ });
+});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment