Skip to content

Instantly share code, notes, and snippets.

@mceachen
Created July 11, 2020 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mceachen/52a9ae7b51c247d5d02d38727d1f0101 to your computer and use it in GitHub Desktop.
Save mceachen/52a9ae7b51c247d5d02d38727d1f0101 to your computer and use it in GitHub Desktop.
Serial collection of a SyncOrAsync array applied against a function
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