-
Notifications
You must be signed in to change notification settings - Fork 0
/
unmaze.js
88 lines (68 loc) · 2.05 KB
/
unmaze.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
71
72
73
74
75
76
77
const poke = require('./bulbasaur')
const Helpers = require('./helpers')
function unmaze(obj) {
return new Unmaze(obj)
}
class Unmaze extends Helpers {
constructor(object) {
super()
var _internalObj = { ...object }
this.getInternalObj = () => ({ ..._internalObj })
this.setInternalObj = (payload) => {
_internalObj = payload
}
this.path = null
this.key = null
this.value = null
this.ofChainCount = 0
}
get obj() {
return this.getInternalObj()
}
get(key) {
this.key = key
this.value = this.getValueOf(key, this.obj)
this.path = this.getPathTo(key, this.obj)
return this
}
of(key) {
// count .of() chain to make sure this.path includes the steps added by chained .of() methods
++this.ofChainCount
const parent = this.getValueOf(key, this.obj)
this.value = parent[this.key]
this.path = [
...this.getPathTo(key, this.obj),
...this.path.reverse().slice(0, this.ofChainCount).reverse()
]
return this
}
in(key) {
return this.of(key)
}
set set(val) {
const { path } = this
let pathToProp = 'this.obj';
// accumulate path to prop as an executable string
for (let i = 0; i < path.length; ++i) {
pathToProp += `['${path[i]}']`
}
// add assignment part to the executable string
const assignValueToProp = pathToProp + `=${JSON.stringify(val)}`
// tell javascript to evaluate executable string
// which is something like this.obj[key1][key2] = val
// TODO: This should use the this.setInternalObj function instead of manipulating it directly.
eval(assignValueToProp)
}
}
// TODO: Create a method that gives user the ability to use value of path and also set it.
// Something like:
// o.get('someKey').use((val, set) => {
// const newVal = val.map(...)
// set(newVal)
// })
// Initialize the object wrapped with unmaze
const o = unmaze(poke)
o.get('level').set = 10454545
console.log(o.path)
console.log(JSON.stringify(o.obj, null, 3))
console.log('new value: ____________', o.get('level').value)