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