Skip to content

Commit cbcbb35

Browse files
committed
feat(array): add filterByPredicates
1 parent 2d3fecb commit cbcbb35

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
title: Filter by predicates
3+
category: Array
4+
---
5+
6+
**JavaScript version**
7+
8+
```js
9+
const filterByPredicates = (arr, predicates, condition = "and") => arr.filter(
10+
item => condition === "and" ? predicates.every(func => func(item)) : predicates.some(func => func(item))
11+
)
12+
```
13+
14+
**TypeScript version**
15+
16+
```js
17+
const filterByPredicates = <T, _>(
18+
arr: T[],
19+
predicates: Array<(val: T) => boolean>,
20+
condition: "and" | "or" = "and"
21+
): T[] => arr.filter(
22+
item => condition === "and" ? predicates.every(func => func(item)) : predicates.some(func => func(item))
23+
)
24+
```
25+
26+
**Example**
27+
28+
```js
29+
const nums = [-2, -1, 0, 1, 2, 3.1];
30+
const isEven = num => num % 2 === 0;
31+
const isPositive = num => num > 0;
32+
filterByPredicates(nums, [isPositive, Number.isInteger], "and"); // [1, 2]
33+
filterByPredicates(nums, [isEven, isPositive], "or"); // [-2, 0, 1, 2, 3.1]
34+
```

0 commit comments

Comments
 (0)