Skip to content

Commit 41fbc7d

Browse files
committed
2 parents 015327a + 2a7571e commit 41fbc7d

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

JavaScript/7-delete.js

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

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