In my database, I have a collection of individuals organized in the following structure:
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']},
];
I want to filter these individuals based on whether they have friends or not. Additionally, I want to leverage the Predicate of the Array.filter
function by lifting it as follows:
const peopleWithoutFriends = people.filter(withoutFriends);
console.log(peopleWithoutFriends);
const peopleWithFriends = people.filter(withFriends);
console.log(peopleWithFriends);
To accomplish this, I can create a generic by
function like this:
const by = x => i => {
return Boolean(get(i, x));
};
const withFriends = by('friends.length');
const peopleWithFriends = people.filter(withFriends);
console.log(peopleWithFriends);
Challenge: Creating a new function for peopleWithoutFriends
would require writing an entirely different logic.
const notBy = x => i => {
return !Boolean(get(i, x));
};
const withOutFriends = notBy('friends.length');
const peopleWithoutFriends = people.filter(withOutFriends);
Instead of duplicating my by
function, I prefer to compose smaller functions together.
Inquiry:
How can I effectively implement and utilize small functions such as: flow
, Boolean
, get
, curry
, not
, and how can I compose withFriends
and withoutFriends
Predicates for filtering my list of people
using Array.filter?
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'), // Not sure about the arity here, is it possible to lift with curry?
);
const peopleWithFriends = people.filter(withFriends);
console.log(peopleWithFriends);
const withoutFriends = flow(not, withFriends);
const peopleWithoutFriends = people.filter(withoutFriends);
console.log(peopleWithoutFriends);