Skip to content

Commit

Permalink
feat(array): add filterByPredicates
Browse files Browse the repository at this point in the history
  • Loading branch information
librz committed Sep 5, 2022
1 parent 2d3fecb commit cbcbb35
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions snippets/array/filter-by-predicates.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
title: Filter by predicates
category: Array
---

**JavaScript version**

```js
const filterByPredicates = (arr, predicates, condition = "and") => arr.filter(
item => condition === "and" ? predicates.every(func => func(item)) : predicates.some(func => func(item))
)
```

**TypeScript version**

```js
const filterByPredicates = <T, _>(
arr: T[],
predicates: Array<(val: T) => boolean>,
condition: "and" | "or" = "and"
): T[] => arr.filter(
item => condition === "and" ? predicates.every(func => func(item)) : predicates.some(func => func(item))
)
```

**Example**

```js
const nums = [-2, -1, 0, 1, 2, 3.1];
const isEven = num => num % 2 === 0;
const isPositive = num => num > 0;
filterByPredicates(nums, [isPositive, Number.isInteger], "and"); // [1, 2]
filterByPredicates(nums, [isEven, isPositive], "or"); // [-2, 0, 1, 2, 3.1]
```

0 comments on commit cbcbb35

Please sign in to comment.