File size: 1,685 Bytes
161cb23
 
7667cef
 
161cb23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
export const THRESHOLD = 0.55;

const ASSET_QUERY = new URL(import.meta.url).search;
const WORKER_URL = new URL(`./score-worker.js${ASSET_QUERY}`, import.meta.url);

class ScoreWorker {
  constructor() {
    this.worker = new Worker(WORKER_URL, { type: "module" });
    this.pending = new Map();
    this.nextId = 1;
    this.worker.addEventListener("message", (event) => this.settle(event.data));
  }

  settle({ id, result, error }) {
    const job = this.pending.get(id);
    this.pending.delete(id);
    if (error) {
      job.reject(new Error(error));
    } else {
      job.resolve(result);
    }
  }

  score(code) {
    const id = this.nextId;
    this.nextId += 1;
    return new Promise((resolve, reject) => {
      this.pending.set(id, { resolve, reject });
      this.worker.postMessage({ id, code, threshold: THRESHOLD });
    });
  }
}

export function createScorer() {
  const cores = navigator.hardwareConcurrency || 4;
  const workers = Array.from({ length: Math.min(4, Math.max(2, cores - 1)) }, () => new ScoreWorker());
  let turn = 0;

  function scoreOne(code) {
    turn = (turn + 1) % workers.length;
    return workers[turn].score(code);
  }

  async function scoreAll(codes, onProgress = () => {}) {
    const results = new Array(codes.length);
    let cursor = 0;
    let completed = 0;

    async function drain(worker) {
      while (cursor < codes.length) {
        const index = cursor;
        cursor += 1;
        results[index] = await worker.score(codes[index]);
        completed += 1;
        onProgress(completed, codes.length);
      }
    }

    await Promise.all(workers.map(drain));
    return results;
  }

  return { scoreOne, scoreAll };
}