-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
53 lines (46 loc) · 1.28 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
const { isArray } = Array
const { set, each } = require('libnested')
module.exports = depnest
function depnest (...args) {
if (isArray(args[0])) return arrayToObject(args[0])
else if (typeof args[0] === 'string') return nestOne(...args)
else if (typeof args[0] === 'object') return nestObject(...args)
throw new Error(`depnest: incorrect arguments! got: ${JSON.stringify(args)}`)
}
function nestOne (path, value = true) {
var out = {}
setNest(out, path, value)
return out
}
function nestObject (object) {
var out = {}
each(object, (value, path) => {
setNest(out, path, value)
})
return out
}
function setNest (out, path, value) {
if (isArray(value)) {
value = arrayToObject(value)
} else if (typeof value === 'object') {
value = nestObject(value)
}
set(out, Path(path), value)
}
function Path (stringOrArray) {
if (typeof stringOrArray === 'string') {
return stringOrArray.split('.')
} else if (isArray(stringOrArray)) {
return stringOrArray.reduce((sofar, next) => {
return [...sofar, ...Path(next)]
}, [])
}
throw new Error(`depnest: path must be either string or array, got: ${JSON.stringify(stringOrArray)}`)
}
function arrayToObject (array) {
var out = {}
array.forEach(path => {
set(out, Path(path), true)
})
return out
}