find
find
(predicate: Predicate) => (collection: Collection) => Value | undefined
Find the first value which passes a condition.
const gt1 = n => n > 1 const findGt1 = find(gt1) findGt1([1, 2, 3]) // is 2 findGt1([0, 1]) // is undefined findGt1({ a: 1, b: 2, c: 3 }) // is 2
const gt1 = (n: number) => n > 1 const findGt1 = find(gt1) findGt1([1, 2, 3]) // is 2 findGt1([0, 1]) // is undefined findGt1({ a: 1, b: 2, c: 3 }) // is 2
const gt1 = n => n > 1 const findGt1 = find(gt1) findGt1([1, 2, 3]) // is 2 findGt1([0, 1]) // is undefined findGt1({ a: 1, b: 2, c: 3 }) // is 2
const gt1 = (n: number) => n > 1 const findGt1 = find(gt1) findGt1([1, 2, 3]) // is 2 findGt1([0, 1]) // is undefined findGt1({ a: 1, b: 2, c: 3 }) // is 2
Sometimes we want to find a value that passes a condition. Below, we want to find our neighbor Tom's number to invite him for some barbecue.
const directory = { 101: { name: 'meg', phone: '555-1873' }, 102: { name: 'tom', phone: '555-7692' }, 103: { name: 'ken', phone: '555-4405' }, } const findTom = find(resident => resident.name === 'tom') const tom = findTom(directory) console.log(tom.phone) // is 555-7692
type Resident = { name: string phone: string } type Directory = Record<number, Resident> const directory: Directory = { 101: { name: 'meg', phone: '555-1873' }, 102: { name: 'tom', phone: '555-7692' }, 103: { name: 'ken', phone: '555-4405' }, } const findTom = find((resident: Resident) => resident.name === 'tom')<Directory> const tom = findTom(directory) as Resident console.log(tom.phone) // is 555-7692
const directory = { 101: { name: 'meg', phone: '555-1873' }, 102: { name: 'tom', phone: '555-7692' }, 103: { name: 'ken', phone: '555-4405' }, } const findTom = find( resident => resident.name === 'tom' ) const tom = findTom(directory) console.log(tom.phone) // is 555-7692
type Resident = { name: string phone: string } type Directory = Record<number, Resident> const directory: Directory = { 101: { name: 'meg', phone: '555-1873' }, 102: { name: 'tom', phone: '555-7692' }, 103: { name: 'ken', phone: '555-4405' }, } const findTom = find( (resident: Resident) => resident.name === 'tom' )<Directory> const tom = findTom(directory) as Resident console.log(tom.phone) // is 555-7692