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.

有帮助吗?

解决方案 2

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"}}}

其他提示

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":{}}}}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top