Skip to content

Commit 6de4f73

Browse files
committed
Calculate transaction delta
1 parent ea367a8 commit 6de4f73

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

JavaScript/4-delta.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
'use strict';
2+
3+
function Transaction() {}
4+
5+
Transaction.start = (data) => {
6+
console.log('start transaction');
7+
let delta = {};
8+
9+
const methods = {
10+
commit: () => {
11+
console.log('commit transaction');
12+
Object.assign(data, delta);
13+
delta = {};
14+
},
15+
rollback: () => {
16+
console.log('rollback transaction');
17+
delta = {};
18+
},
19+
clone: () => {
20+
console.log('clone transaction');
21+
const cloned = Transaction.start(data);
22+
Object.assign(cloned.delta, delta);
23+
return cloned;
24+
},
25+
delta: () => delta
26+
};
27+
28+
const proxy = new Proxy(data, {
29+
get(target, key) {
30+
if (key === Symbol.iterator) {
31+
const changes = Object.keys(delta);
32+
const keys = Object.keys(target).concat(changes);
33+
const props = keys.filter((x, i, a) => a.indexOf(x) === i);
34+
return props[Symbol.iterator]();
35+
}
36+
if (methods.hasOwnProperty(key)) return methods[key];
37+
if (delta.hasOwnProperty(key)) return delta[key];
38+
return target[key];
39+
},
40+
getOwnPropertyDescriptor: (target, key) => (
41+
Object.getOwnPropertyDescriptor(
42+
delta.hasOwnProperty(key) ? delta : target, key
43+
)
44+
),
45+
set(target, key, val) {
46+
console.log('set', key, val);
47+
if (target[key] === val) delete delta[key];
48+
else delta[key] = val;
49+
return true;
50+
}
51+
});
52+
return proxy;
53+
};
54+
55+
// Usage
56+
57+
const data = { name: 'Marcus Aurelius', city: 'Rome', born: 121 };
58+
59+
const transaction = Transaction.start(data);
60+
console.dir({ data, transaction, delta: transaction.delta() });
61+
62+
transaction.name = 'Mao Zedong';
63+
transaction.born = 1893;
64+
console.dir({ data, transaction, delta: transaction.delta() });
65+
66+
transaction.commit();
67+
console.dir({ data, transaction, delta: transaction.delta() });
68+
69+
transaction.city = 'Shaoshan';
70+
console.dir({ data, transaction, delta: transaction.delta() });
71+
72+
transaction.rollback();
73+
console.dir({ data, transaction, delta: transaction.delta() });

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy