-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
98 lines (83 loc) · 2.14 KB
/
Copy pathindex.js
File metadata and controls
98 lines (83 loc) · 2.14 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
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
91
92
93
94
95
96
97
98
const mergeDeep = require('../mergeDeep')
const isObject = require('./isObject')
const castString = require('./castString')
const toBoolean = require('./toBoolean')
const toJSON = require('./toJSON')
const { isPassthrough } = require('../passthrough')
const toObjectLoose = (array, output, from, defaults) => {
return array.reduce((object, key) => {
if (output[key] === undefined) {
return object
}
object[key] = cast(
output[key],
from[key] || defaults[1][key] || defaults[0][key]
)
return object
}, {})
}
const toObject = (output, from, isStrict, defaults) => {
if (isStrict) {
return Object.keys(from).reduce((object, key) => {
object[key] = cast(output[key], from[key], output[key] !== undefined)
return object
}, {})
}
return mergeDeep(
toObjectLoose(Object.keys(from), output, from, defaults),
toObjectLoose(Object.keys(output), output, from, defaults)
)
}
const toArray = (output, from, isStrict) => {
if (
!isObject(output) &&
typeof output !== 'string' &&
!Array.isArray(output)
) {
return []
}
const converted = isObject(output)
? [output]
: Array.isArray(output)
? output
: castString(output)
return converted.map((value, index) => {
isStrict = isStrict === undefined ? true : from[index] !== undefined
return cast(value, from[index] || from[0], isStrict, [value, from[0]])
})
}
const cast = (output, from, isStrict = true, defaults) => {
if (typeof from === 'undefined' || from === null || output === 'undefined') {
return output
}
if (isPassthrough(from)) {
return output
}
if (isObject(from)) {
return toObject(toJSON(output), from, isStrict, defaults)
}
if (Array.isArray(from)) {
return toArray(output, from, isStrict)
}
switch (typeof from) {
case 'number': {
const converted = Number(output)
return isNaN(converted) ? from : converted
}
case 'string':
return `${output}`
case 'boolean':
return toBoolean(output)
default:
return output
}
}
module.exports = {
cast,
toArray,
toObject,
castString,
toBoolean,
toJSON,
isObject,
}