Async Filter
Async Filter - Explanation
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
async function asyncFilter(arr, predicate) {
const results = await Promise.all(arr.map(predicate));
return arr.filter((_, i) => results[i]);
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(n)
Uses memory proportional to input size