ramda 进化函数示例

ramda evolve function example

来自 Ramda Repl:

var tomato  = {firstName: '  Tomato ', data: {elapsed: 100, remaining: 1400}, id:123};

为什么这样做:

var transformations = {
  firstName: ()=>'Potato'
};
// => {"data": {"elapsed": 100, "remaining": 1400}, "firstName": "Potato", "id": 123}

但这不是:

var transformations = {
  firstName:'Potato'
};
//=>{"data": {"elapsed": 100, "remaining": 1400}, "firstName": "  Tomato ", "id": 123}

R.evolve(变换,番茄);

R.evolve

Creates a new object by recursively evolving a shallow copy of object, according to the transformation functions. All non-primitive properties are copied by reference.

A transformation function will not be invoked if its corresponding key does not exist in the evolved object.

简而言之,转换必须是一个函数

Why does this work:

var transformations = {
  firstName: ()=>'Potato'
};

因为()=>'Potato'是一个函数

But this doesnt:

var transformations = {
  firstName:'Potato'
};

因为 'Potato' 是一个 字符串 不是一个函数

在提供的转换不是函数的情况下,原始值。

这是 evolve 的源代码。我 加粗 您的示例到达输出的代码路径

module.exports = _curry2(function evolve(transformations, object) {
  var result = {};
  var transformation, key, type;
  for (key in object) {
    transformation = transformations[key];
    type = typeof transformation;
    <b>result[key] = type === 'function'</b>                 ? transformation(object[key])
                : <b>transformation && type === 'object'</b> ? evolve(transformation, object[key])
                                                      : <b>object[key]</b>;
  }
  return result;
});

@naomik 解释了原因 - 但如果出于某种原因你需要 使用进化,你可以这样做:

{
    firstName: R.always('Potato')
}

值得记住的是,给转换的参数是当前值,如果键不存在,它不会添加任何东西。