Async Filter

Async Filter - Explanation

어려움 비동기 O(n) O(n)

Problem Summary

Write an async filter function that filters array items with an async predicate.

Go to Problem →

Detailed Explanation

이 문제는 **비동기 filter**를 구현하여 비동기 조건 함수로 필터링하는 방법을 학습합니다. ## 핵심 개념: 비동기 Filter 비동기 조건 함수의 결과로 배열을 필터링합니다. ### 구현 ```javascript async function asyncFilter(arr, predicate) { const results = await Promise.all(arr.map(predicate)); return arr.filter((_, i) => results[i]); } ``` ### 왜 map을 먼저 실행하는가? 1. 모든 조건을 병렬로 평가 (map + Promise.all) 2. 결과 배열을 사용해 필터링 ### 단계별 분석 ```javascript const arr = [1, 2, 3, 4]; const predicate = async x => x > 2; // 1단계: 모든 조건 평가 results = await Promise.all([false, false, true, true]); // 2단계: 결과로 필터링 arr.filter((_, i) => results[i]) // [3, 4] ``` ### 왜 직접 filter를 사용할 수 없는가? ```javascript // 이렇게 하면 안 됨! arr.filter(async x => await predicate(x)) // filter는 Promise를 truthy로 판단함 ``` 비동기 조건은 먼저 평가하고 결과로 필터링해야 합니다.

Solution Code

solution.js
async function asyncFilter(arr, predicate) {
  const results = await Promise.all(arr.map(predicate));
  return arr.filter((_, i) => results[i]);
}

Key Concepts from This Problem

1. 비동기 filter
2. 조건 함수
3. 병렬 평가
4. 인덱스 필터링

Common Mistakes

filter 콜백에 직접 async 함수를 사용하면 안 됩니다
Promise 객체는 truthy로 평가되어 모든 요소가 통과합니다
조건 결과 배열과 원본 배열의 인덱스가 일치해야 합니다

Hints

Hint 1: 먼저 모든 predicate를 실행하고 결과로 필터링하세요.

Complexity Analysis

Time Complexity

O(n)

Grows linearly with input size

Space Complexity

O(n)

Uses memory proportional to input size

Related Tags

#비동기 #filter #Promise.all