Last active
September 7, 2016 21:16
-
-
Save ssube/46715cd6baf67b5beec6e8e5c15928d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const data = { | |
args: [ | |
['foo.bar.baz', 1], | |
['foo.bar.biz', 2], | |
['fin', 3] | |
], | |
env: { | |
'APEX_FIN_BIN': 7, | |
'APEX_FAN_BAN': 8, | |
'NOPE_NOPE_NOPE': 9, | |
'NPPE': 10 | |
} | |
}; | |
function setKeyAt(target, keys, value) { | |
const tail = keys.pop(); | |
const leaf = keys.reduce((step, next) => { | |
if (!step[next]) { | |
step[next] = {}; | |
} | |
return step[next]; | |
}, target); | |
leaf[tail] = value; | |
} | |
function resolvePath(path, {del, prefix, clutter}) { | |
const rest = path.split(del); | |
const [head] = rest; | |
if (prefix && head !== prefix) { | |
return [clutter, ...rest]; | |
} else { | |
return rest; | |
} | |
} | |
function treeLike(flat, {del = '.', prefix, clutter}) { | |
const out = {}; | |
Object.keys(flat).forEach(key => { | |
const value = flat[key]; | |
setKeyAt(out, resolvePath(key, {del, prefix, clutter}), value); | |
}); | |
return out; | |
} | |
function fromEnv(env) { | |
return treeLike(env, {clutter: 'env', del: '_', prefix: 'APEX'}); | |
} | |
function fromArgs(args) { | |
const flat = args.reduce((p, [k, v]) => (p[k] = v, p), {}); | |
return treeLike(flat, {clutter: 'args', del: '.', prefix: null}); | |
} | |
console.log(fromEnv(data.env), fromArgs(data.args)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment