async filter extensions

This commit is contained in:
Rory&
2025-11-25 18:16:58 +01:00
parent 1b8c5c3dd5
commit df6f2c06d1
2 changed files with 16 additions and 0 deletions

View File

@@ -41,6 +41,12 @@ describe("Array extensions", () => {
assert.strictEqual(sum, 6);
});
it("filterAsync", async () => {
const arr = [1, 2, 3, 4, 5];
const even = await arr.filterAsync(async (n) => n % 2 === 0);
assert.deepEqual(even, [2, 4]);
});
it("remove", () => {
const arr = [1, 2, 3, 4, 5];
arr.remove(3);

View File

@@ -22,6 +22,7 @@ declare global {
partition(filter: (elem: T) => boolean): [T[], T[]];
single(filter: (elem: T) => boolean): T | null;
forEachAsync(callback: (elem: T, index: number, array: T[]) => Promise<void>): Promise<void>;
filterAsync(callback: (elem: T, index: number, array: T[]) => Promise<boolean>): Promise<T[]>;
remove(item: T): void;
first(): T | undefined;
last(): T | undefined;
@@ -55,6 +56,11 @@ export async function arrayForEachAsync<T>(array: T[], callback: (elem: T, index
await Promise.all(array.map(callback));
}
export async function arrayFilterAsync<T>(array: T[], callback: (elem: T, index: number, array: T[]) => Promise<boolean>): Promise<T[]> {
const results = await Promise.all(array.map(callback));
return array.filter((_, index) => results[index]);
}
export function arrayRemove<T>(this: T[], item: T): void {
const index = this.indexOf(item);
if (index > -1) {
@@ -112,6 +118,10 @@ if (!Array.prototype.forEachAsync)
Array.prototype.forEachAsync = function <T>(this: T[], callback: (elem: T, index: number, array: T[]) => Promise<void>) {
return arrayForEachAsync(this, callback);
};
if (!Array.prototype.filterAsync)
Array.prototype.filterAsync = function <T>(this: T[], callback: (elem: T, index: number, array: T[]) => Promise<boolean>) {
return arrayFilterAsync(this, callback);
};
if (!Array.prototype.remove)
Array.prototype.remove = function <T>(this: T[], item: T) {
return arrayRemove.call(this, item);