Skip to content Skip to sidebar Skip to footer

Looking For An Fp Algorithm To Compose Objects From Dot-separated Strings

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-separate

Solution 1:

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

Solution 2:

A fully functional variant:

functiontraverse(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;
}
functioncreate(path, value) {
    if (!path.length)
        return value;
    var tree = {};
    tree[path[0]] = create(path.slice(1), value);
    return tree;
}

functionset(tree, pathstring, value) {
    return traverse(tree, pathstring.split("."), function(path) {
        returncreate(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"}}}

Post a Comment for "Looking For An Fp Algorithm To Compose Objects From Dot-separated Strings"