-
Notifications
You must be signed in to change notification settings - Fork 0
/
mighty.js
90 lines (68 loc) · 2.1 KB
/
mighty.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
78
79
80
81
82
83
84
85
86
87
88
89
90
const util = require('./util')
class Mighty {
constructor(obj, options = {}) {
if (options.clone)
this.obj = util.clone(obj)
else
this.obj = obj
}
morph(original, destination) {
this.destination = destination
this.value = util.extract(this.obj, original)
const composed = util.build(this.destination, this.value)
util.assign(this.obj, composed)
this.remove(original)
return this
}
combine(keys, destination, separator) {
this.destination = destination
const data = []
keys.forEach((key, index) => {
const value = util.extract(this.obj, key)
data.push({ key, value })
this.remove(key)
}, this)
this.value = util.merge(data)
const composed = util.build(this.destination, this.value)
util.assign(this.obj, composed)
return this
}
add(destination, value) {
this.destination = destination
this.value = value
const composed = util.build(this.destination, this.value)
util.assign(this.obj, composed)
return this
}
remove(key) {
util.clear(this.obj, key)
return this
}
coerce(destination, type) {
if (this.destination) {
type = destination
} else {
this.destination = destination
this.value = util.extract(this.obj, this.destination)
}
switch(type) {
case 'number': {
const coerced = util.build(this.destination, parseFloat(this.value))
Object.assign(this.obj, coerced)
return this
}
case 'string': {
const coerced = util.build(this.destination, this.value.toString())
Object.assign(this.obj, coerced)
return this
}
// TODO add case 'array' to coerce comma separates values to an array
}
}
get result() {
return this.obj
}
}
module.exports = (obj, options) => {
return new Mighty(obj, options)
}