Add asyncFilter

This commit is contained in:
Florian Duros 2024-11-14 17:54:54 +01:00
parent 9a126795a8
commit 6533a6b642
No known key found for this signature in database
GPG key ID: A5BBB4041B493F15
2 changed files with 22 additions and 0 deletions

View file

@ -328,6 +328,16 @@ export async function asyncSome<T>(values: Iterable<T>, predicate: (value: T) =>
return false; return false;
} }
/**
* Async version of Array.filter.
* @param values
* @param predicate
*/
export async function asyncFilter<T>(values: Array<T>, predicate: (value: T) => Promise<boolean>): Promise<Array<T>> {
const results = await Promise.all(values.map(predicate));
return values.filter((_, i) => results[i]);
}
export function filterBoolean<T>(values: Array<T | null | undefined>): T[] { export function filterBoolean<T>(values: Array<T | null | undefined>): T[] {
return values.filter(Boolean) as T[]; return values.filter(Boolean) as T[];
} }

View file

@ -23,6 +23,7 @@ import {
concat, concat,
asyncEvery, asyncEvery,
asyncSome, asyncSome,
asyncFilter,
} from "../../../src/utils/arrays"; } from "../../../src/utils/arrays";
type TestParams = { input: number[]; output: number[] }; type TestParams = { input: number[]; output: number[] };
@ -460,4 +461,15 @@ describe("arrays", () => {
expect(predicate).toHaveBeenCalledWith(2); 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]);
});
});
}); });