Add asyncFilter
This commit is contained in:
parent
9a126795a8
commit
6533a6b642
2 changed files with 22 additions and 0 deletions
|
@ -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[];
|
||||||
}
|
}
|
||||||
|
|
|
@ -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]);
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue