Skip to content

Commit 485a10d

Browse files
authored
added async filter
1 parent 980c520 commit 485a10d

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

async-filter.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const asyncCall = async element => {
2+
return new Promise((resolve, reject) => {
3+
setTimeout(() => {
4+
resolve(element % 2 === 0);
5+
}, 5000);
6+
});
7+
};
8+
9+
const asyncFilter = async (array, callback) => {
10+
const data = await Promise.all(
11+
array.map(async element => {
12+
const predicate = await callback(element);
13+
return predicate ? element : undefined;
14+
})
15+
);
16+
17+
return data.filter(item => item !== undefined);
18+
};
19+
20+
// driver code
21+
const input = [1, 2, 3, 4, 5, 6];
22+
23+
asyncFilter(input, asyncCall).then(response => {
24+
console.log(response);
25+
});

0 commit comments

Comments
 (0)