summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorRory& <root@rory.gay>2025-11-25 18:16:58 +0100
committerRory& <root@rory.gay>2025-11-25 18:16:58 +0100
commitdf6f2c06d16b3ebfaa50e8d7f16cea5917b35bd2 (patch)
tree8d5c0cd2b099863dd4dc857eb9e08e561bfab4c8 /src
parentadd missing user flags (diff)
downloadserver-ts-df6f2c06d16b3ebfaa50e8d7f16cea5917b35bd2.tar.xz
async filter extensions
Diffstat (limited to 'src')
-rw-r--r--src/util/util/extensions/Array.test.ts6
-rw-r--r--src/util/util/extensions/Array.ts10
2 files changed, 16 insertions, 0 deletions
diff --git a/src/util/util/extensions/Array.test.ts b/src/util/util/extensions/Array.test.ts

index 6395ddcf..d41442c9 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 611a8437..c32b86ce 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<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);