寻找一个FP算法组成由点分隔的字符串对象 [英] Looking for an FP algorithm to compose objects from dot-separated strings

查看:97
本文介绍了寻找一个FP算法组成由点分隔的字符串对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解决使用功能的编程特定的问题。我的猜测是,折应该做的工作,但到目前为止,该解决方案已躲避我。

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.

这是一个圆点分隔字符串开始像ABC我想建立一个Javascript对象,在JS文字符号看起来像:

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

该算法应该接受一个种子的对象下手。在previous例如种子将 {}

如果我提供的 {A:{F:任何其他}} 作为种子,其结果必然是

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.

我使用JavaScript,因为这是这个现实世界的问题出现了,其中的语言,在这里我将实行计划生育的解决方案,我希望能找到通过询问这里。

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.

编辑:主要的问题我想解决的的如何避免可变对象的。 JS是有点过于宽松有关添加/删除属性,在这种情况下,我想肯定会有的FP程序的运行过程中无任何副作用。

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.

推荐答案

一个全功能的变体:

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

这篇关于寻找一个FP算法组成由点分隔的字符串对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆