Skip to content

Commit ea367a8

Browse files
committed
Implement getOwnPropertyDescriptor handler
1 parent 0aa1d05 commit ea367a8

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

JavaScript/3-descriptor.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+
};
20+
21+
return new Proxy(data, {
22+
get(target, key) {
23+
if (methods.hasOwnProperty(key)) return methods[key];
24+
if (delta.hasOwnProperty(key)) return delta[key];
25+
return target[key];
26+
},
27+
getOwnPropertyDescriptor: (target, key) => (
28+
Object.getOwnPropertyDescriptor(
29+
delta.hasOwnProperty(key) ? delta : target, key
30+
)
31+
),
32+
set(target, key, val) {
33+
console.log('set', key, val);
34+
if (target[key] === val) delete delta[key];
35+
else delta[key] = val;
36+
return true;
37+
}
38+
});
39+
};
40+
41+
// Usage
42+
43+
const data = { name: 'Marcus Aurelius', city: 'Rome', born: 121 };
44+
45+
const transaction = Transaction.start(data);
46+
console.log(JSON.stringify(data), JSON.stringify(transaction));
47+
console.dir({ data, transaction });
48+
49+
transaction.name = 'Mao Zedong';
50+
transaction.born = 1893;
51+
console.log('JSON:', JSON.stringify(data), JSON.stringify(transaction));
52+
console.dir({ data, transaction });
53+
54+
transaction.commit();
55+
console.log('JSON:', JSON.stringify(data), JSON.stringify(transaction));
56+
console.dir({ data, transaction });
57+
58+
transaction.city = 'Shaoshan';
59+
console.log('JSON:', JSON.stringify(data), JSON.stringify(transaction));
60+
console.dir({ data, transaction });
61+
62+
transaction.rollback();
63+
console.log('JSON:', JSON.stringify(data), JSON.stringify(transaction));
64+
console.dir({ data, transaction });

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