Skip to content

Instantly share code, notes, and snippets.

@ssube
Last active September 7, 2016 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssube/46715cd6baf67b5beec6e8e5c15928d0 to your computer and use it in GitHub Desktop.
Save ssube/46715cd6baf67b5beec6e8e5c15928d0 to your computer and use it in GitHub Desktop.
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