Last active
August 22, 2023 05:38
-
-
Save orion55/e87686370755edffe817b60daf273f40 to your computer and use it in GitHub Desktop.
filterUsers
This file contains hidden or 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
interface User { | |
type: 'user'; | |
name: string; | |
age: number; | |
occupation: string; | |
} | |
interface Admin { | |
type: 'admin'; | |
name: string; | |
age: number; | |
role: string; | |
} | |
export type Person = User | Admin; | |
export function filterUsers(persons: Person[], criteria: Partial<Omit<User, 'type'>>): User[] { | |
return persons.filter(isUser).filter((user) => { | |
const criteriaKeys = Object.keys(criteria) as (keyof Omit<User, 'type'>)[]; | |
return criteriaKeys.every((fieldName) => { | |
return user[fieldName] === criteria[fieldName]; | |
}); | |
}); | |
} | |
console.log('Users of age 23:'); | |
filterUsers( | |
persons, | |
{ | |
age: 23 | |
} | |
).forEach(logPerson); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment