[英]Is there a lodash/fp equivalent of Ramda's 'evolve' function?
Looking for a lodash equivalent of Ramda's evolve : 寻找与Ramda 的演变相当的破破烂烂的东西 :
const transformForDisplay = (item) => {
const transform = {
body: truncate({ length: 100 }),
title: truncate({ length: 50 })
}
return R.evolve(transform, item)
}
Which returns an object containing all of the original fields from 'item' but truncating the 'body' and 'title' fields if they exist. 它返回一个对象,其中包含来自“ item”的所有原始字段,但会截断“ body”和“ title”字段(如果存在)。
Edit: this works. 编辑:这有效。 Anything more pithy?
还有什么更辣吗?
const transformForDisplay = (item) => {
const transform = {
body: truncate,
title: truncate
}
const mapValuesWithKey = _.mapValues.convert({ cap: false })
return mapValuesWithKey((x, key) => transform[key] ? transform[key](x) : x)(item)
}
I wasn't able to find any built-in equivalent. 我找不到任何内置的等效项。 Here's how you might implement
evolve
yourself. 这是您实现自我
evolve
。
It's pretty much what you already had, except I used _.getOr
to avoid having to repeat transform[key]
, and I added a recursive call to evolve
when necessary. 除了我使用
_.getOr
来避免必须重复执行transform[key]
,并添加了一个递归调用以在必要时进行evolve
,这几乎是您已经拥有的。
// Implementation const mapValuesWithKey = _.mapValues.convert({cap: false}); function evolve(transformations) { return item => mapValuesWithKey((value, key) => { const transformation = _.getOr(_.identity)(key)(transformations); const type = typeof transformation; return type === 'function' ? transformation(value) : transformation && type === 'object' ? evolve(transformation)(value) : value; })(item); } // Example const tomato = { firstName: ' Tomato ', data: {elapsed: 100, remaining: 1400}, id: 123 }; const transformations = { firstName: _.trim, lastName: _.trim, // Will not get invoked. data: {elapsed: _.add(1), remaining: _.add(-1)}, id: null, // Will have no effect. } const result = evolve(transformations)(tomato); console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script> <script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.fp.min.js"></script>
Just tried to use more lodash functions: 刚刚尝试使用更多lodash函数:
const evolve = _.curry((transformations, item) =>
_.mapValues.convert({ cap: false })((value, key) => {
const transformation = _.propOr(identity, key, transformations);
return _.cond([
[_.isFunction, t => t(value)],
[_.isObject, t => evolve(t, value)],
[_.T, _.always(value)],
])(transformation);
}, item)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.