[英]ramda evolve function example
From Ramda Repl: 从Ramda Repl:
var tomato = {firstName: ' Tomato ', data: {elapsed: 100, remaining: 1400}, id:123};
Why does this work: 为什么这样做:
var transformations = {
firstName: ()=>'Potato'
};
// => {"data": {"elapsed": 100, "remaining": 1400}, "firstName": "Potato", "id": 123}
But this doesnt: 但这不是:
var transformations = {
firstName:'Potato'
};
//=>{"data": {"elapsed": 100, "remaining": 1400}, "firstName": " Tomato ", "id": 123}
R.evolve(transformations, tomato); R.evolve(转化,番茄);
Creates a new object by recursively evolving a shallow copy of
object
, according to thetransformation
functions .创建由递归演进的浅表复制一个新的对象
object
,根据该transformation
函数 。 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.如果在进化对象中不存在
transformation
函数的键,则transformation
函数不会被调用。
In short, the transformation must be a function . 简而言之,转换必须是一个函数 。
Why does this work:
为什么这样做:
var transformations = { firstName: ()=>'Potato' };
Because ()=>'Potato'
is a function 因为
()=>'Potato'
是一个函数
But this doesnt:
但这不是:
var transformations = { firstName:'Potato' };
Because 'Potato'
is a string , not a function . 因为
'Potato'
是一个字符串 , 而不是一个函数 。
In such a case when the provided transformation is not a function, the original value. 在这种情况下,如果提供的转换不是函数,则为原始值。
Here's the source code for evolve
. 这是
evolve
的源代码。 I bolded the code path your example takes to arrive at the output 我加粗了示例得出输出的代码路径
module.exports = _curry2(function evolve(transformations, object) {
var result = {};
var transformation, key, type;
for (key in object) {
transformation = transformations[key];
type = typeof transformation;
result[key] = type === 'function' ? transformation(object[key])
:
transformation && type === 'object' ? evolve(transformation, object[key])
:
object[key];
}
return result;
});
@naomik's explained why - but if for some reason you need to use evolve, you could do: @naomik解释了原因-但如果由于某些原因需要使用Evolution,则可以执行以下操作:
{
firstName: R.always('Potato')
}
It's worth remembering that the argument given to the transform is the current value, and if the key doesn't exist it won't add anything. 值得记住的是,赋予转换的参数是当前值,如果键不存在,则不会添加任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.