如何通过函数组合实现人员数组过滤的正反断言?
用函数式组合实现人员筛选的断言函数
我来帮你梳理一下怎么用函数式组合(结合Lodash的工具函数)实现你想要的withFriends和withoutFriends断言函数,既能避免重复编写类似by/notBy的函数,又能保持逻辑的简洁性。
核心思路
我们可以通过柯里化固定get的路径参数,再通过函数流组合get、Boolean和取反操作,来构建需要的断言函数:
- 先把
_.get柯里化,固定要获取的路径为'friends.length',得到一个只接收人员对象的函数,用于提取好友列表的长度。 - 用
_.flow把“提取长度”和“转成布尔值”组合起来,得到判断是否有朋友的断言。 - 对于反向逻辑,直接用Lodash的
_.negate(或者自定义的not函数)对withFriends的结果取反即可。
完整实现代码
const { flow, get, curry, negate } = require('lodash'); const people = [ {name: 'jenny', friends: ['jeff']}, {name: 'frank', friends: ['jeff', 'ross']}, {name: 'sarah', friends: []}, {name: 'jeff', friends: ['jenny', 'frank']}, {name: 'russ', friends: []}, {name: 'calvin', friends: []}, {name: 'ross', friends: ['frank']}, ]; // 自定义取反函数(也可以直接用lodash的negate) const not = value => !value; // 构建withFriends断言:先获取friends.length,再转成布尔值 const withFriends = flow( curry(get)('friends.length'), // 柯里化get,固定路径后得到接收对象的函数 Boolean // 将长度值转为布尔(0→false,非0→true) ); // 构建withoutFriends断言:对withFriends的结果取反 const withoutFriends = flow(withFriends, not); // 或者用lodash的negate更简洁:const withoutFriends = negate(withFriends); // 测试筛选 const peopleWithFriends = people.filter(withFriends); const peopleWithoutFriends = people.filter(withoutFriends); console.log('有朋友的人员:', peopleWithFriends); console.log('无朋友的人员:', peopleWithoutFriends);
代码解释
curry(get)('friends.length'):把_.get转成柯里化函数后,先传入路径参数,得到一个新函数,这个函数只需要接收人员对象,就能返回该对象的friends.length值。flow(...):Lodash的flow会按从左到右的顺序执行函数,把前一个函数的输出作为后一个的输入。这里就是先获取好友长度,再转成布尔值,最终得到判断是否有朋友的断言。- 取反逻辑:不管是用自定义的
not函数结合flow,还是直接用_.negate,都是对withFriends的结果取反,避免了重复编写类似notBy的逻辑。
测试结果
运行代码后,你会得到:
- 有朋友的人员:
jenny、frank、jeff、ross - 无朋友的人员:
sarah、russ、calvin
内容的提问来源于stack exchange,提问作者John Abraham
相关产品推荐
相关产品推荐

