-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
76 lines (67 loc) · 1.97 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
71
72
73
74
75
76
function using(data, async) {
return {
// Return actual value
value() {
return data
},
// Call function and return new instance of wrapper (no mutations)
do(func) {
return async && data instanceof Promise
? using(data.then(func), async)
: using(func(data), async)
},
// Call function if condition is truthly (functions allowed)
// otherwise return current wrapper
doIf(condition, func) {
if(typeof condition === 'function') {
return condition(data) ? this.do(func) : this
} else {
return condition ? this.do(func) : this
}
},
// Call function if condition is falsy (functions allowed)
// otherwise return current wrapper
doUnless(condition, func) {
if(typeof condition === 'function') {
return this.doIf((data) => !condition(data), func)
} else {
return this.doIf(!condition, func)
}
},
// Call funcTruthy if condition is truthly (functions allowed)
// Call funcFalsy if condition is falsy (functions allowed)
doIfElse(condition, funcTruthy, funcFalsy) {
if(typeof condition === 'function') {
return condition(data) ? this.do(funcTruthy) : this.do(funcFalsy)
} else {
return condition ? this.do(funcTruthy) : this.do(funcFalsy)
}
},
// Call only one passed functions (based on value)
switch(value, map) {
let key;
if (typeof value === 'function') {
key = value(data)
} else if (typeof value === 'object') {
key = data
map = value
} else {
key = value
}
if(map[key]) {
return this.do(map[key])
} else if (map['default']) {
return this.do(map['default'])
} else {
return this
}
},
// Call function without mutating data
debug(logFunction) {
logFunction(data)
return this
},
}
}
using.async = function (data) { return using(data, true) }
module.exports = using