findKey
findKey
(predicate: Predicate) => (collection: EntryCollection) => Key
Find the first key that passes a condition
const findKeyWhereValGt1 = findKey(val => val > 1) findKeyWhereValGt1([0, 1, 2]) // is 2 findKeyWhereValGt1([1, 2, 3]) // is 1 findKeyWhereValGt1([0, 1]) // is undefined findKeyWhereValGt1({ a: 1, b: 2 }) // is 'b'
const findKeyWhereValGt1 = findKey((val: number) => val > 1) findKeyWhereValGt1([0, 1, 2]) // is 2 findKeyWhereValGt1([1, 2, 3]) // is 1 findKeyWhereValGt1([0, 1]) // is undefined findKeyWhereValGt1({ a: 1, b: 2 }) // is 'b'
const findKeyWhereValGt1 = findKey(val => val > 1) findKeyWhereValGt1([0, 1, 2]) // is 2 findKeyWhereValGt1([1, 2, 3]) // is 1 findKeyWhereValGt1([0, 1]) // is undefined findKeyWhereValGt1({ a: 1, b: 2 }) // is 'b'
const findKeyWhereValGt1 = findKey( (val: number) => val > 1 ) findKeyWhereValGt1([0, 1, 2]) // is 2 findKeyWhereValGt1([1, 2, 3]) // is 1 findKeyWhereValGt1([0, 1]) // is undefined findKeyWhereValGt1({ a: 1, b: 2 }) // is 'b'
Sometimes we want to find a key based off a condition. Below, we are heading to a cat cafe and want to schedule time to pet a kitten. Let's find one.
const cats = { charlie: { age: 'cat' }, luna: { age: 'kitten' }, max: { age: 'old cat' }, leo: { age: 'kitten' }, } const findKitten = findKey(cat => cat.age === 'kitten') const name = findKitten(cats) console.log(name) // is luna
type Cat = { age: string } type Cats = Record<string, Cat> const cats: Cats = { charlie: { age: 'cat' }, luna: { age: 'kitten' }, max: { age: 'old cat' }, leo: { age: 'kitten' }, } const findKitten = findKey((cat: Cat) => cat.age === 'kitten')<Cats> const name = findKitten(cats) console.log(name) // is luna
const cats = { charlie: { age: 'cat' }, luna: { age: 'kitten' }, max: { age: 'old cat' }, leo: { age: 'kitten' }, } const findKitten = findKey( cat => cat.age === 'kitten' ) const name = findKitten(cats) console.log(name) // is luna
type Cat = { age: string } type Cats = Record<string, Cat> const cats: Cats = { charlie: { age: 'cat' }, luna: { age: 'kitten' }, max: { age: 'old cat' }, leo: { age: 'kitten' }, } const findKitten = findKey( (cat: Cat) => cat.age === 'kitten' )<Cats> const name = findKitten(cats) console.log(name) // is luna