-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex1.js
More file actions
50 lines (43 loc) · 1.06 KB
/
ex1.js
File metadata and controls
50 lines (43 loc) · 1.06 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
'use strict';
/*
Problem:
Implement makeReader(initial) to expose two readers:
- getBinding(): closes over a binding and observes updates
- getSnapshot(): snapshots the initial value at creation time (no JSON cloning)
API:
- set(next): rebinds the internal value
- mutate(key, value): mutates the current object by setting a property
Constraints:
- Snapshot must not change after mutations or rebinds.
- Binding reader must observe both mutation and rebind.
*/
function shallowClone(value) {
if (value && typeof value === 'object') {
return Array.isArray(value)
? value.slice()
: Object.assign({}, value);
}
return value;
}
function makeReader(initial) {
let current = initial;
const snapshot = shallowClone(initial);
return {
getBinding() {
return current;
},
getSnapshot() {
return snapshot;
},
set(next) {
current = next;
},
mutate(key, value) {
if (current && typeof current === 'object') {
current[key] = value;
}
return current;
}
};
}
module.exports = { makeReader };