Skip to content

Commit

Permalink
improved change tracking not to track if value is same
Browse files Browse the repository at this point in the history
  • Loading branch information
Damith88 committed Mar 16, 2021
1 parent 633dfd1 commit 9ab9d13
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
dist
coverage
node_modules
10 changes: 10 additions & 0 deletions src/__tests__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
24 changes: 24 additions & 0 deletions src/deep-equal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// 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;
10 changes: 10 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import deepEqual from './deep-equal';

/**
* The key used to get the handler.
*/
Expand Down Expand Up @@ -237,6 +239,14 @@ export class Sakota<T extends object> implements ProxyHandler<T> {
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;
Expand Down

0 comments on commit 9ab9d13

Please sign in to comment.