mirror of
https://github.com/voltrevo/ValueScript.git
synced 2026-04-18 03:00:27 -04:00
Add concurrencyLimit to parallelMap
This commit is contained in:
@@ -3,8 +3,23 @@ import { thread } from 'value-script';
|
||||
export default function parallelMap<Value, MappedValue>(
|
||||
values: Value[],
|
||||
mapper: (value: Value) => MappedValue,
|
||||
concurrencyLimit = 10,
|
||||
) {
|
||||
return values
|
||||
.map(v => thread(() => mapper(v)))
|
||||
.map(t => t());
|
||||
let poolSize = Math.min(values.length, concurrencyLimit);
|
||||
|
||||
const pool = values
|
||||
.slice(0, poolSize)
|
||||
.map(v => thread(() => mapper(v)));
|
||||
|
||||
let results: MappedValue[] = [];
|
||||
|
||||
for (let i = 0; i < values.length; i++) {
|
||||
results[i] = pool[i % poolSize]();
|
||||
|
||||
if (i + poolSize < values.length) {
|
||||
pool[i % poolSize] = thread(() => mapper(values[i + poolSize]));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user