-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
37 lines (33 loc) · 806 Bytes
/
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
'use strict';
module.exports = function expand(value) {
if (!isObject(value)) return value;
const res = Array.isArray(value) ? [] : {};
for (const key of Object.keys(value)) {
set(res, key, expand(value[key]));
}
return res;
};
function set(obj, prop, val) {
const segs = split(prop);
const last = segs.pop();
while (segs.length) {
const key = segs.shift();
obj = obj[key] || (obj[key] = {});
}
obj[last] = val;
}
function split(str) {
const segs = str.split('.');
const keys = [];
for (let i = 0; i < segs.length; i++) {
const seg = segs[i];
while (seg.slice(-1) === '\\') {
seg = seg.slice(0, -1) + '.' + (segs[++i] || '');
}
keys.push(seg);
}
return keys;
}
function isObject(val) {
return val !== null && typeof val === 'object';
}