gpt4 book ai didi

javascript - ramda 进化函数示例

转载 作者:行者123 更新时间:2023-11-30 08:28:01 24 4
gpt4 key购买 nike

来自 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;
});

关于javascript - ramda 进化函数示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42135771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com