Created
July 11, 2020 21:14
-
-
Save mceachen/52a9ae7b51c247d5d02d38727d1f0101 to your computer and use it in GitHub Desktop.
Serial collection of a SyncOrAsync array applied against a function
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
export type SyncOrAsync<T> = T | Promise<T> | |
export type Maybe<T> = T | undefined | |
export type MaybeSyncOrAsync<T> = Maybe<SyncOrAsync<Maybe<T>>> | |
/** | |
* Serialized promise gathering and compaction | |
*/ | |
export async function thenCollect<T1, T2>( | |
arr: MaybeSyncOrAsync<MaybeSyncOrAsync<T1>[]>, | |
f: (t: T1) => MaybeSyncOrAsync<T2> | |
): Promise<T2[]> { | |
const result: T2[] = [] | |
for (const eaP of toA(await arr)) { | |
if (eaP != null) { | |
const ea = await eaP | |
if (ea != null) { | |
const r = await f(ea) | |
if (r != null) result.push(r) | |
} | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment