diff --git a/src/utils/arrays.ts b/src/utils/arrays.ts index 99c69b9891..a7f97766b4 100644 --- a/src/utils/arrays.ts +++ b/src/utils/arrays.ts @@ -328,6 +328,16 @@ export async function asyncSome(values: Iterable, predicate: (value: T) => return false; } +/** + * Async version of Array.filter. + * @param values + * @param predicate + */ +export async function asyncFilter(values: Array, predicate: (value: T) => Promise): Promise> { + const results = await Promise.all(values.map(predicate)); + return values.filter((_, i) => results[i]); +} + export function filterBoolean(values: Array): T[] { return values.filter(Boolean) as T[]; } diff --git a/test/unit-tests/utils/arrays-test.ts b/test/unit-tests/utils/arrays-test.ts index 53baed8be3..9bd8f15510 100644 --- a/test/unit-tests/utils/arrays-test.ts +++ b/test/unit-tests/utils/arrays-test.ts @@ -23,6 +23,7 @@ import { concat, asyncEvery, asyncSome, + asyncFilter, } from "../../../src/utils/arrays"; type TestParams = { input: number[]; output: number[] }; @@ -460,4 +461,15 @@ describe("arrays", () => { expect(predicate).toHaveBeenCalledWith(2); }); }); + + describe("asyncFilter", () => { + it("when called with an empty array, it should return an empty array", async () => { + expect(await asyncFilter([], jest.fn().mockResolvedValue(true))).toEqual([]); + }); + + it("should filter the content", async () => { + const predicate = jest.fn().mockImplementation((value) => Promise.resolve(value === 2)); + expect(await asyncFilter([1, 2, 3], predicate)).toEqual([2]); + }); + }); });