mirror of
https://github.com/spacebarchat/server.git
synced 2026-03-30 22:35:40 +00:00
async filter extensions
This commit is contained in:
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user