javascript - 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)
我什至不知道这是否可行,但我很确定我可以做一些更清晰或更易读的事情。
你有什么想法吗?
解决方案
尽量不要把 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
推荐阅读
- java - JMS 连接在连接后关闭并每 30 秒重试一次
- mysql - MySQL-如何使用 Group By 获取值
- c# - WCF 和自定义身份验证(用户名/密码)
- css - 为什么 react-bootstrap 的 Progressbar 不起作用?
- apache-kafka - 如何使用 JMX 获取 kafka 代理状态
- ios - 如何在可本地化的文件字符串中命名键
- javascript - 使用单击功能从数组中删除项目
- mongodb - 使用 NestJS 和 Mongo 获取相关数据
- ansible - 使用 ansible 同步模块在两个远程主机之间同步文件
- reactjs - 使用库 vue-native-scripts 安装 Vue-Native 的问题