Javascript 如何将函数提升和组合在一起?
我有此结构中的人员列表:Javascript 如何将函数提升和组合在一起?,javascript,functional-programming,lodash,ramda.js,lifting,Javascript,Functional Programming,Lodash,Ramda.js,Lifting,我有此结构中的人员列表: 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
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']},
];
我想用两种方式过滤掉人:有朋友和没有朋友;此外,我希望数组.filter的
const peopleWithoutFriends = people.filter(withoutFriends);
console.log(peopleWithoutFriends);
const peopleWithFriends = people.filter(withFriends);
console.log(peopleWithFriends);
我可以通过如下方式显式编写by
函数来实现此行为:
const by = x => i => {
return Boolean(get(i, x));
};
const withFriends = by('friends.length');
const peopleWithFriends = people.filter(withFriends);
console.log(peopleWithFriends);
问题:如果我想要相反的结果,我需要显式地为没有朋友的人编写一个全新的函数
const notBy = x => i => {
return !Boolean(get(i, x));
};
const withOutFriends = notBy('friends.length');
const peopleWithoutFriends = people.filter(withOutFriends);
我不想通过
函数两次编写我的。我宁愿将较小的函数组合在一起
问题:
如何编写和使用小函数,如:和编写withFriends
和WithOfFriends
谓词。筛选人员列表
答复:
由于带/不带友元函数的结果是布尔值,因此可以对其中一个函数的结果求反(或求补)以获得另一个函数的结果。此外,函数的arity为1(它们操作的对象)
Lodash/fp:
const{flow,get,isEmpty,negate}=\;
康斯特人=[
{姓名:'jenny',朋友:['jeff']},
{姓名:'frank',朋友:['jeff','ross']},
{姓名:'莎拉',朋友:[]},
{姓名:'jeff',朋友:['jenny','frank']},
{姓名:'罗斯',朋友:[]},
{姓名:'卡尔文',朋友:[]},
{姓名:'ross',朋友:['frank']},
];
const withoutFriends=flow(get('friends'),isEmpty);//创建一个获取friends数组的函数,并检查它是否为空
const withFriends=否定(withoutFriends);//否定没有朋友的结果
const peopleWithFriends=people.filter(withFriends);
console.log(peopleWithFriends);
const peopleWithoutFriends=people.filter(withoutFriends);
console.log(没有朋友的人)代码>
在函数式编程中,有时术语比实际应用程序更容易混淆:)“流和管道都从右到左执行序列…”-我想你的意思是“从左到右”。@user633183-事实上:)修复了。还请注意,Ramda的拒绝
在这里可能很有用R.reject(foo,xs)
相当于R.filter(R.complete(foo,xs)
。您可能对lodash/fp也感兴趣
const {flow, get, curry} = 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']},
];
const not = i => !i;
const withFriends = i => flow(
Boolean,
get(i, 'friends.length'), // arity of this is 2 so might be harder to lift, is it possible tho with curry?
); // No idea what i'm doing here.
const peopleWithFriends = people.filter(withFriends);
console.log(peopleWithFriends);
const withoutFriends = flow(not, withFriends);
const peopleWithoutFriends = people.filter(withoutFriends);
console.log(peopleWithoutFriends);