Skip to content
← Public packages

@kentcdodds/codemod-runner

Run codemods over your own saved packages: scan, dry-run with real publish checks and diffs, apply, and revert.

src/async-pool.ts

27 lines · 815 B · TypeScript
/**
 * Map `items` with a bounded number of in-flight mapper calls. Results stay
 * in input order. Used to read package files without issuing one RPC at a
 * time, which is what blew the 90s export sandbox on multi-package scan pages.
 */
export async function mapPool<T, R>(
	items: Array<T>,
	concurrency: number,
	mapper: (item: T) => Promise<R>,
): Promise<Array<R>> {
	if (items.length === 0) return []
	const workerCount = Math.min(Math.max(concurrency, 1), items.length)
	const results = new Array<R>(items.length)
	let nextIndex = 0

	async function worker() {
		while (true) {
			const index = nextIndex
			nextIndex += 1
			if (index >= items.length) return
			results[index] = await mapper(items[index]!)
		}
	}

	await Promise.all(Array.from({ length: workerCount }, () => worker()))
	return results
}