Skip to content

predicate #27

@innerstella

Description

@innerstella

기본 개념

  • 어떤 값을 받아서 boolean을 반환하는 함수
  • 주로 "조건을 검사하는 함수"로 사용됨
  • 배열 메서드나 필터링 로직에서 자주 사용됨
  • 코드의 가독성을 높이고 재사용 가능한 조건 로직을 만드는데 유용함

사용 예시

  • 배열 메서드 : 여기서 num => num % 2 === 0 가 predicate 함수
const numbers = [1, 2, 3, 4, 5, 6];

// filter: predicate가 true인 요소만 남김
const evenNumbers = numbers.filter(num => num % 2 === 0);
// [2, 4, 6]
  • 타입 가드
// 타입 가드로서의 predicate
function isString(value: unknown): value is string {
  return typeof value === 'string';
}

const data: unknown = "hello";

if (isString(data)) {
  // 이 블록 안에서 data는 string 타입으로 좁혀짐
  console.log(data.toUpperCase());
}

실무 코드 적용

  • 쿼리 키를 정확히 모를 때 찾는 법
// 쿼리 키가 [getZelda, {id: 1234}, any] 이런 형식으로 올 때]

 const portfolioQueries = queryCache.findAll({
     predicate: query => {
         const queryKey = query.queryKey;
         
         return (
             Array.isArray(queryKey) &&
             queryKey.length > 0 &&
             typeof queryKey[0] === 'string' &&
             queryKey[0].includes('getPortfolio') &&
             queryKey[1]?.id === props.portfolioID
          );
      }

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions