From df6f2c06d16b3ebfaa50e8d7f16cea5917b35bd2 Mon Sep 17 00:00:00 2001 From: Rory& Date: Tue, 25 Nov 2025 18:16:58 +0100 Subject: [PATCH] async filter extensions --- src/util/util/extensions/Array.test.ts | 6 ++++++ src/util/util/extensions/Array.ts | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/util/util/extensions/Array.test.ts b/src/util/util/extensions/Array.test.ts index 6395ddcf4..d41442c99 100644 --- a/src/util/util/extensions/Array.test.ts +++ b/src/util/util/extensions/Array.test.ts @@ -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); diff --git a/src/util/util/extensions/Array.ts b/src/util/util/extensions/Array.ts index 611a84373..c32b86ce8 100644 --- a/src/util/util/extensions/Array.ts +++ b/src/util/util/extensions/Array.ts @@ -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): Promise; + filterAsync(callback: (elem: T, index: number, array: T[]) => Promise): Promise; remove(item: T): void; first(): T | undefined; last(): T | undefined; @@ -55,6 +56,11 @@ export async function arrayForEachAsync(array: T[], callback: (elem: T, index await Promise.all(array.map(callback)); } +export async function arrayFilterAsync(array: T[], callback: (elem: T, index: number, array: T[]) => Promise): Promise { + const results = await Promise.all(array.map(callback)); + return array.filter((_, index) => results[index]); +} + export function arrayRemove(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 (this: T[], callback: (elem: T, index: number, array: T[]) => Promise) { return arrayForEachAsync(this, callback); }; +if (!Array.prototype.filterAsync) + Array.prototype.filterAsync = function (this: T[], callback: (elem: T, index: number, array: T[]) => Promise) { + return arrayFilterAsync(this, callback); + }; if (!Array.prototype.remove) Array.prototype.remove = function (this: T[], item: T) { return arrayRemove.call(this, item);