Looking for an FP algorithm to compose objects from dot-separated strings

♀尐吖头ヾ 提交于 2019-12-01 13:04:37

问题


I am trying to solve a specific problem using functional programming. My guess is that a fold should do the job, but so far the solution has eluded me.

Starting from a dot-separated string like "a.b.c" I want to build a Javascript object which in JS literal notation would look like:

obj = {a:{b:{c:"whatever"}}}

The algorithm should accept a seed object to start with. In the previous example the seed would be {}.

If I provided {a:{f:"whatever else"}} as seed, the result would be

{a:{f:"whatever else",b:{c:"whatever"}}}

I hope my description is clear enough. I am not talking about string manipulation. I want to create proper objects.

I am using Javascript because that's the language where this real-world problem has arisen and where I will implement the FP solution which I hope to find by asking here.

EDIT: the main issue I am trying to tackle is how to avoid mutable objects. JS is somehow too lenient about adding/removing attributes and in this case I want to be sure that there will be no side effects during the run of the FP routine.


回答1:


A fully functional variant:

function traverse(tree, path, leftover) {
    if (!tree || !path.length)
        return leftover(path);
    var ntree = {};
    for (var p in tree)
        ntree[p] = tree[p];
    ntree[path[0]] = traverse(tree[path[0]], path.slice(1), leftover);
    return ntree;
}
function create(path, value) {
    if (!path.length)
        return value;
    var tree = {};
    tree[path[0]] = create(path.slice(1), value);
    return tree;
}

function set(tree, pathstring, value) {
    return traverse(tree, pathstring.split("."), function(path) {
        return create(path, value);
    });
}

var seed = {a:{f:"whatever else"}};
var obj = set(seed, "a.b.c", "whatever")
    // {"a":{"f":"whatever else","b":{"c":"whatever"}}}
set({}, "a.b.c", "whatever")
    // {"a":{"b":{"c":"whatever"}}}



回答2:


var seed = {},
    str = "a.b.c";
str.split(".").reduce(function(o, p) {
    return p in o ? o[p] : (o[p] = {});
}, seed);

console.log(seed); // {"a":{"b":{"c":{}}}}


来源:https://stackoverflow.com/questions/22864748/looking-for-an-fp-algorithm-to-compose-objects-from-dot-separated-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!