Created
March 4, 2018 23:04
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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