From 0c2d5a0c30081034f9c0892c36904f533260b4f5 Mon Sep 17 00:00:00 2001 From: Damith Karunaratne Date: Tue, 16 Mar 2021 11:30:06 +0530 Subject: [PATCH] improved change tracking not to track if value is same --- .gitignore | 1 + src/__tests__/index.spec.ts | 10 ++++++++++ src/deep-equal.ts | 25 +++++++++++++++++++++++++ src/index.ts | 10 ++++++++++ 4 files changed, 46 insertions(+) create mode 100644 src/deep-equal.ts diff --git a/.gitignore b/.gitignore index 009af54..5bcb6fe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ dist coverage +node_modules diff --git a/src/__tests__/index.spec.ts b/src/__tests__/index.spec.ts index 8f253f5..1778c84 100644 --- a/src/__tests__/index.spec.ts +++ b/src/__tests__/index.spec.ts @@ -585,6 +585,16 @@ describe('Sakota', () => { expect(proxy.__sakota__.getChanges('', /a/)).toEqual({ $set: { a: 1000 } }); expect(proxy.__sakota__.getChanges('', /c/)).toEqual({ $unset: { c: true } }); }); + + it('should not track changes if value is not changed', () => { + const proxy = Sakota.create({ a: 10, b: 20, c: 30 }); + proxy.a = 10; + expect(proxy.__sakota__.getChanges()).toEqual({}); + proxy.a = 12; + expect(proxy.__sakota__.getChanges()).toEqual({ $set: { a: 12 } }); + proxy.a = 10; + expect(proxy.__sakota__.getChanges()).toEqual({}); + }); }); describe('hasChanges', () => { diff --git a/src/deep-equal.ts b/src/deep-equal.ts new file mode 100644 index 0000000..5057a06 --- /dev/null +++ b/src/deep-equal.ts @@ -0,0 +1,25 @@ +// ref: https://stackoverflow.com/a/25456134 + +const deepEqual = (x: any, y: any) => { + if (x === y) { + return true; + } else if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) { + if (Object.keys(x).length != Object.keys(y).length) { + return false; + } + + for (var prop in x) { + if (y.hasOwnProperty(prop)) { + if (!deepEqual(x[prop], y[prop])) + return false; + } else { + return false; + } + } + + return true; + } + return false; +}; + +export default deepEqual; \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 6ab645d..c6e9f91 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,5 @@ +import deepEqual from './deep-equal'; + /** * The key used to get the handler. */ @@ -237,6 +239,14 @@ export class Sakota implements ProxyHandler { if (!this.diff) { this.diff = { $set: {}, $unset: {} }; } + if (obj.hasOwnProperty(key) && deepEqual(obj[key], val)) { + if (this.diff.$unset[key] || this.diff.$set[key]) { + delete this.diff.$unset[key]; + delete this.diff.$set[key]; + this.onChange(); + } + return true; + } delete this.diff.$unset[key]; delete this.kids[key]; this.diff.$set[key] = val;