From cbcbb35f7cbca8339d5a75fcd763bfb80149415b Mon Sep 17 00:00:00 2001 From: librz Date: Mon, 5 Sep 2022 11:45:34 +0800 Subject: [PATCH] feat(array): add filterByPredicates --- snippets/array/filter-by-predicates.md | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 snippets/array/filter-by-predicates.md diff --git a/snippets/array/filter-by-predicates.md b/snippets/array/filter-by-predicates.md new file mode 100644 index 00000000..faf02f34 --- /dev/null +++ b/snippets/array/filter-by-predicates.md @@ -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 = ( + 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] +```