【发布时间】:2019-10-05 17:03:15
【问题描述】:
我有这个结构中的人员列表:
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 的Predicate 为lifted,如下所示:
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 函数两次。我宁愿把更小的函数组合在一起。
问题:
我如何编写和使用小函数,例如:flowBooleangetcurrynot 并在列表中为我的 Array.filter 编写 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);
【问题讨论】:
-
您可能也对
lodash/fp感兴趣
标签: javascript functional-programming lodash ramda.js lifting