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

improved change tracking not to track if value is same #24

Merged
merged 3 commits into from
Mar 17, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
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
26 changes: 26 additions & 0 deletions src/deep-equal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// 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 (key in obj && 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