From 382135c78e4a817f9d844d2fbebc185d5062ed87 Mon Sep 17 00:00:00 2001 From: lifegpc Date: Mon, 12 Jun 2023 14:03:55 +0800 Subject: [PATCH] Update asyncFilter --- utils.ts | 40 ++++++++++++++++++++++++++++++++++------ utils_test.ts | 25 ++++++++++++++++++++++--- 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/utils.ts b/utils.ts index a746ff9..c454dcb 100644 --- a/utils.ts +++ b/utils.ts @@ -81,14 +81,25 @@ export function try_remove_sync( } } -export async function asyncFilter( - arr: T[], - callback: (element: T, index: number, array: T[]) => Promise, +const fail = Symbol(); + +export async function asyncFilter( + arr: ArrayLike, + callback: ( + this: V | undefined, + element: T, + index: number, + array: ArrayLike, + ) => Promise, + thisArg?: V, ): Promise { - const fail = Symbol(); const t = <[T][]> (await Promise.all( - arr.map(async (item, index, array) => - (await callback(item, index, array)) ? [item] : fail + map( + arr, + async (item, index, array) => + (await callback.apply(thisArg, [item, index, array])) + ? [item] + : fail, ), )).filter((i) => i !== fail); return t.map((t) => t[0]); @@ -231,3 +242,20 @@ export async function asyncEvery( } return true; } + +export function map( + arr: ArrayLike, + callback: ( + this: S | undefined, + element: T, + index: number, + array: ArrayLike, + ) => V, + thisArg?: S, +) { + const re: V[] = []; + for (let i = 0; i < arr.length; i++) { + re.push(callback.apply(thisArg, [arr[i], i, arr])); + } + return re; +} diff --git a/utils_test.ts b/utils_test.ts index 16fe149..f1b0241 100644 --- a/utils_test.ts +++ b/utils_test.ts @@ -7,6 +7,7 @@ import { asyncForEach, calFileMd5, filterFilename, + map, promiseState, PromiseStatus, sleep, @@ -47,11 +48,19 @@ Deno.test("asyncFilter_test", async () => { }); assertEquals(r, [3]); const e = [new Promise((res) => setTimeout(() => res(100), 100))]; - const v = await asyncFilter(e, async (t) => { - const s = await promiseState(t); + const v = await asyncFilter(e, async function (d) { + assertEquals(this, t); + const s = await promiseState(d); return s.status === PromiseStatus.Pending; - }); + }, t); assertEquals(v, e); + const e2 = { 0: e[0], length: 1 }; + const v2 = await asyncFilter(e2, async function (d) { + assertEquals(this, t); + const s = await promiseState(d); + return s.status === PromiseStatus.Pending; + }, t); + assertEquals(v, v2); await Promise.allSettled(e); }); @@ -128,3 +137,13 @@ Deno.test("asyncEvery_test", async () => { false, ); }); + +Deno.test("map_test", () => { + const arr = { 0: 1, 1: 2, length: 2 }; + const d = { d: 1 }; + const re = map(arr, function (n) { + assertEquals(this, d); + return n + 2; + }, d); + assertEquals(re, [3, 4]); +});