首页 > 解决方案 > lodash fp 和重构一些现有代码

问题描述

我正在学习函数式编程,并且正在尝试使用 lodash FP 重构一段旧代码。

这是我的代码:

_.filter(x => isIdInArray(x)(xs))(otherXs)

读起来太复杂了,让我觉得有点奇怪(气味?)

我的问题是 x 值,即 isIdInArray 的第一个参数是这样声明的:

const getId = _.get('id');
const isIdInArray = _.compose(_.includes, getId);

我不能以这种方式使用我的 lodash 过滤器功能:

_.filter(isIdInArray(xs))(otherXs)

我什至不知道这是否可行,但我很确定我可以做一些更清晰或更易读的事情。

你有什么想法吗?

标签: javascriptrefactoringlodash

解决方案


尽量不要把 lodash 给你的所有花哨的功能都塞进一行。在一行中有一个复杂的机制可能看起来不错,但如果你不能再阅读它,它根本就没有多大帮助。

为了管理收藏,我通常使用这样的方法:

var collection = [{id: 'a', someField: 1}, {id:'b', someField: 2}];
var theIdsYoureLookingFor = ['a'];

var filtered = collection
                .filter(anyObject => _.includes(theIdsYoureLookingFor, anyObject.id))
                .map(anyObject => anyObject.someField);

alert(filtered); // alerts 1

它解析对象的集合,过滤具有您认为有效的 id 的对象,然后将这些对象映射到某个字段。

也不要使用变量名称,例如:x、xs


推荐阅读