Skip to content

Instantly share code, notes, and snippets.

@cqsd
Created July 27, 2021 07:01
Show Gist options
  • Save cqsd/ef672ce559449737bfcc5438f5c86e3d to your computer and use it in GitHub Desktop.
Save cqsd/ef672ce559449737bfcc5438f5c86e3d to your computer and use it in GitHub Desktop.
Typescript utils

Some functions I end up using in just about every js project.

/**
* Type guard for non-empty values. Maintains type information when used with Array.filter
*
* Example
* >>> const a1: number[] = [1, null, 3].filter((e) => !!e) // this compiles with type errors
* >>> const a2: number[] = [1, null, 3].filter(notEmpty) // this compiles without
* @param v any
*/
export const nonEmpty = <T>(v: T | null | undefined): v is T => v !== null && v !== undefined;
export const range = (n: number) => [...new Array(n).keys()];
export const sleep = (n: number) => new Promise((r) => setTimeout(r, n));
export function* toGenerator<T>(arr: Array<T>) {
yield* arr;
}
interface poolOptions {
concurrency: number;
}
const defaultPoolOptions = (): poolOptions => ({
concurrency: 4,
});
/**
* Process an async generator concurrently
* @param resources an async generator
* @param options
* @param fn a function to process the generated items
*/
export const withConcurrencyLimit = async <T>(
resources: Generator<T>,
options: Partial<poolOptions> = {},
fn: (arg: T) => Promise<void>
): Promise<void> => {
const _options = { ...defaultPoolOptions(), options };
const worker = async () => {
for await (const r of resources) {
await fn(r);
}
};
const pool = range(_options.concurrency).map(() => worker());
await Promise.all(pool);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment