Last active
May 4, 2024 19:58
-
-
Save nullmastermind/965bdfb8a1b98fda6432a2e34b05da76 to your computer and use it in GitHub Desktop.
Lodash async forEach implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { map } from 'lodash'; | |
async function asyncForEach<T>( | |
items: Array<T> | null | undefined, | |
iter: (v: T, k: number) => Promise<boolean | void>, | |
): Promise<void>; | |
async function asyncForEach<T, K extends string>( | |
items: Record<K, T> | null | undefined, | |
iter: (v: T, k: K) => Promise<boolean | void>, | |
): Promise<void>; | |
async function asyncForEach<T, K extends number | string>( | |
items: Array<T> | Record<K, T> | null | undefined, | |
iter: (v: T, k: K) => Promise<boolean | void>, | |
) { | |
const kvItems = map(items, (value, index) => ({ | |
v: value as T, | |
k: index as K, | |
})); | |
for (const kvItem of kvItems) { | |
if ((await iter(kvItem.v, kvItem.k)) === false) break; | |
} | |
} | |
export default asyncForEach; |
Author
nullmastermind
commented
May 4, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment