Skip to content

Commit 6a58198

Browse files
committed
Spreadsheet implementation on Proxy
1 parent 4ad126b commit 6a58198

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

JavaScript/3-proxy.js

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
'use strict';
2+
3+
const ROWS = 5;
4+
const columns = ['A', 'B', 'C', 'D', 'E', 'F'];
5+
const data = {};
6+
7+
const table = new Proxy(data, {
8+
get(obj, key) {
9+
console.log('get', key);
10+
const cell = obj[key];
11+
return cell ? cell.value : '';
12+
},
13+
set(obj, key, value) {
14+
console.log('set', key, value);
15+
const type = typeof value;
16+
if (type === 'function') {
17+
const expression = value;
18+
value = expression();
19+
obj[key] = { value, expression };
20+
} else {
21+
obj[key] = { value };
22+
}
23+
return true;
24+
}
25+
});
26+
27+
// Usage
28+
29+
table.A1 = 'city';
30+
table.B1 = 'population';
31+
table.C1 = 'area';
32+
table.D1 = 'density';
33+
table.E1 = 'country';
34+
table.F1 = 'relative';
35+
36+
table.A2 = 'Shanghai';
37+
table.B2 = 24256800;
38+
table.C2 = 6340;
39+
table.D2 = 3826;
40+
table.E2 = 'China';
41+
42+
table.A3 = 'Beijing';
43+
table.B3 = 21516000;
44+
table.C3 = 16411;
45+
table.D3 = 1311;
46+
table.E3 = 'China';
47+
48+
table.A4 = 'Delhi';
49+
table.B4 = 16787941;
50+
table.C4 = 1484;
51+
table.D4 = 11313;
52+
table.E4 = 'India';
53+
54+
table.D5 = () => Math.max(table.D2, table.D3, table.D4);
55+
56+
table.F2 = () => Math.round(table.D2 * 100 / table.D5) + '%';
57+
table.F3 = () => Math.round(table.D3 * 100 / table.D5) + '%';
58+
table.F4 = () => Math.round(table.D4 * 100 / table.D5) + '%';
59+
60+
const output = [];
61+
62+
for (let i = 2; i <= ROWS; i++) {
63+
const row = {};
64+
output[i] = row;
65+
for (const col of columns) {
66+
row[col] = table[col + i];
67+
}
68+
}
69+
70+
console.table(output);

0 commit comments

Comments
 (0)