๐Ÿ’™ Typescript/Typescript Exercises

[TS] TypeScript Exercises 5 ํ•ด์„ ๋ฐ ํ’€์ด

์„ ๋‹ฌ 2023. 7. 17. 20:02
๋ฐ˜์‘ํ˜•

Intro

    Filtering requirements have grown. We need to be
    able to filter any kind of Persons.

 

ํ•„ํ„ฐ๋ง ์š”๊ตฌ์‚ฌํ•ญ์ด ๋Š˜์—ˆ์Šต๋‹ˆ๋‹ค. ์ด์ œ Person์˜ ๋ชจ๋“  ์ข…๋ฅ˜๋ฅผ ๊ตฌ๋ถ„ํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.

 

Exercise

    Fix typing for the filterPersons so that it can filter users
    and return User[] when personType='user' and return Admin[]
    when personType='admin'. Also filterPersons should accept
    partial User/Admin type according to the personType.
    `criteria` argument should behave according to the
    `personType` argument value. `type` field is not allowed in
    the `criteria` field.

 

personType์ด user๋ผ๋ฉด User[]๋ฅผ, personType์ด admin์ด๋ฉด Admin[]๋ฅผ ๋ฆฌํ„ดํ•  ์ˆ˜ ์žˆ๋„๋ก filterPerson์˜ ํƒ€์ž…์„ ๊ณ ์ณ๋ณด์„ธ์š”. filterPerson์€ personType์— ๋”ฐ๋ผ User/Admin ํƒ€์ž…์˜ ์ผ๋ถ€๋ฅผ ๋ฐ›์•„์•ผํ•ฉ๋‹ˆ๋‹ค. criteria ์ธ์ž๋Š” personType ์ธ์ž์˜ ๊ฐ’์— ๋”ฐ๋ผ ๋‹ฌ๋ผ์ง‘๋‹ˆ๋‹ค. type ํ•„๋“œ๋Š” criteria ํ•„๋“œ์— ํ—ˆ์šฉ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

Bonus

    Implement a function `getObjectKeys()` which returns more
    convenient result for any argument given, so that you don't
    need to cast it.

    let criteriaKeys = Object.keys(criteria) as (keyof User)[];
    -->
    let criteriaKeys = getObjectKeys(criteria);

 

์บ์ŠคํŒ…ํ•  ํ•„์š” ์—†์ด ์ฃผ์–ด์ง„ ์ธ์ž์— ๋Œ€ํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋” ํŽธํ•˜๊ฒŒ ๋ฆฌํ„ดํ•˜๋Š” getObjectKeys() ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•ด๋ณด์„ธ์š”

 

Code

const getObjectKeys = <T>(criteria:T) =>  Object.keys(criteria) as (keyof T)[];

export function filterPersons(persons: Person[], personType: "user", criteria: Partial<User>): User[];
export function filterPersons(persons: Person[], personType: "admin", criteria: Partial<Admin>): Admin[];
export function filterPersons(persons: Person[], personType: string, criteria: Partial<Person>): Person[] {
    return persons
        .filter((person) => person.type === personType)
        .filter((person) => {
            let criteriaKeys = getObjectKeys(criteria);
            return criteriaKeys.every((fieldName) => {
                return person[fieldName] === criteria[fieldName];
            });
        });
}

๋ฌธ์ œ์— ๋‚˜์˜จ๋Œ€๋กœ Object.keys(criteria) ๋ถ€๋ถ„์€ getObjectKeys๋ฅผ ์ด์šฉํ•˜์—ฌ ๋”ฐ๋กœ ๋นผ์ฃผ์—ˆ๋‹ค.

criteria์˜ ํƒ€์ž…์ด ๋งค๋ฒˆ ๋‹ฌ๋ผ์ง€๋ฏ€๋กœ ์ œ๋„ค๋ฆญ์„ ์ด์šฉํ–ˆ๋‹ค

 

filterPersons๊ฐ€ Userm Admin Person ๋‹ค์–‘ํ•ด์„œ ๋‹นํ™ฉ์Šค๋Ÿฌ์› ๋Š”๋ฐ ์˜ค๋ฒ„๋กœ๋”ฉ์œผ๋กœ ํ•ด๊ฒฐํ–ˆ๋‹ค.

๊ทธ๋ƒฅ ๋ƒ…๋‹ค ์ •์˜๋ถ€ํ„ฐ ํ•ด๋„ ๋˜๋Š”๊ฑฐ์˜€๋‹ค.

 

From

https://typescript-exercises.github.io/#exercise=6&file=%2Findex.ts

 

TypeScript Exercises

A set of interactive TypeScript exercises

typescript-exercises.github.io

 

๋ฐ˜์‘ํ˜•