我有这个结构中的人员列表:
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']},
];
我想通过两种方式过滤人:有朋友和没有朋友;此外,我希望提升的谓词,Array.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);
问题:如果我想要逆,我需要显式地写一个全新的函数peopleWithoutFriends
const notBy = x => i => {
return !Boolean(get(i, x));
};
const withOutFriends = notBy('friends.length');
const peopleWithoutFriends = people.filter(withOutFriends);
我不想把我的by
函数写两次。我宁愿将较小的功能组合在一起。
问题:
如何在. _ _flow
Boolean
get
curry
not
withFriends
withOutFriends
people
回复:https ://repl.it/@matthewharwood/ChiefWelloffPaintprogram
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);