Skip to content

Instantly share code, notes, and snippets.

@dmeehan1968
Created March 4, 2018 23:04
Show Gist options
  • Save dmeehan1968/37f7fef5e292173846cf9598286bdbf6 to your computer and use it in GitHub Desktop.
Save dmeehan1968/37f7fef5e292173846cf9598286bdbf6 to your computer and use it in GitHub Desktop.
cherryPick - recurse any value, including objects and arrays, returning an array of values that match the predicate
// @flow
type Predicate<T> = T => boolean
export default function cherryPick<T>(memo: Array<T>, predicate: Predicate<T>, subject: T): Array<T> {
if (predicate(subject)) {
return [ ...memo, subject ]
}
if (Array.isArray(subject)) {
return subject.reduce((memo, subject) => cherryPick(memo, predicate, subject), memo)
}
if (subject instanceof Object) {
return Object.keys(subject).reduce((memo, key) => {
// $FlowFixMe: missing indexer property
return cherryPick(memo, predicate, subject[key])
}, memo)
}
return memo
}
import cherryPick from './cherryPick'
const data = {
name: 'Bob',
age: 40,
children: [
{
name: 'Harry',
age: 10
},
{
name: 'Alice',
age: 13
}
],
spouse: {
name: 'Susan',
age: 38
}
};
const childPredicate = subject => typeof subject === 'object' && subject.age <= 16;
const children = cherryPick([], childPredicate, data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment