-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
70 lines (63 loc) · 1.45 KB
/
index.js
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
class ExistentialProxy {
/**
* Proxy wrapper for existential access
* @param terminator
*/
constructor(terminator) {
this.terminator = terminator;
}
/**
* Override get method
* @param target
* @param name
* @returns {Proxy|*}
*/
get(target, name) {
return this.terminator === name ?
target.entity :
new Proxy(target.get(name), this);
}
}
class ExistentialWrapper {
/**
* Lazy wrapper for proxied entities
* @param entity
*/
constructor(entity) {
this.entity = entity;
}
/**
* Getter
* @param key
* @returns {ExistentialWrapper}
*/
get(key) {
return new ExistentialWrapper(this.contains(key) ? this.entity[key] : undefined);
}
/**
* Check if the property is exist
* @param key
* @returns {boolean}
*/
contains(key) {
return this.isObject() && key in this.entity;
}
/**
* Check if it's an object
* @returns {boolean}
*/
isObject() {
return typeof this.entity === 'object' && !!this.entity;
}
}
const DEFAULT_GETTER = '$';
/**
* Existential accessor (terminator $ is mandatory)
* Example: a.b.c.$ <=> a.?b.?c
* @param entity
* @param terminator
* @returns {Proxy}
*/
module.exports = function (entity, terminator = DEFAULT_GETTER) {
return new Proxy(new ExistentialWrapper(entity), new ExistentialProxy(terminator));
};