1

私はこの構造の人々のリストを持っています:

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']},
];

2 つの方法で人を除外したいと思います。友達がいる場合といない場合です。さらに、次のように、の述語持ち上げ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関数を 2 回書きたくありません。より小さな機能を一緒に構成したいと思います。

質問:

次のような小さな関数を作成して使用するにはどうすればよいですか。flow Booleanget curry notwithFriendswithOutFriendspeople

Repl: 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);
4

1 に答える 1