parallelFindIndex.ts

This commit is contained in:
Andrew Morris
2022-05-01 18:03:29 +10:00
parent ac295889f5
commit 89efce6cd3

View File

@@ -0,0 +1,27 @@
import { thread } from 'value-script';
export default function parallelFindIndex<Value>(
values: Value[],
predicate: (value: Value) => boolean,
concurrencyLimit = 10,
): number | undefined {
let poolSize = Math.min(values.length, concurrencyLimit);
const pool = values
.slice(0, poolSize)
.map(v => thread(() => predicate(v)));
for (let i = 0; i < values.length; i++) {
if (pool[i % poolSize]()) {
// When exiting here, everything gets dereferenced, which will notify all
// the other threads to stop working and clean up
return i;
}
if (i + poolSize < values.length) {
pool[i % poolSize] = thread(() => predicate(values[i + poolSize]));
}
}
return undefined;
}