1 | /*
|
---|
2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
---|
3 | Author Tobias Koppers @sokra
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | const binarySearchBounds = require("./binarySearchBounds");
|
---|
9 |
|
---|
10 | /** @typedef {function(number): void} Callback */
|
---|
11 |
|
---|
12 | class ParallelismFactorCalculator {
|
---|
13 | constructor() {
|
---|
14 | /** @type {number[]} */
|
---|
15 | this._rangePoints = [];
|
---|
16 | /** @type {Callback[]} */
|
---|
17 | this._rangeCallbacks = [];
|
---|
18 | }
|
---|
19 |
|
---|
20 | /**
|
---|
21 | * @param {number} start range start
|
---|
22 | * @param {number} end range end
|
---|
23 | * @param {Callback} callback callback
|
---|
24 | * @returns {void}
|
---|
25 | */
|
---|
26 | range(start, end, callback) {
|
---|
27 | if (start === end) return callback(1);
|
---|
28 | this._rangePoints.push(start);
|
---|
29 | this._rangePoints.push(end);
|
---|
30 | this._rangeCallbacks.push(callback);
|
---|
31 | }
|
---|
32 |
|
---|
33 | calculate() {
|
---|
34 | const segments = Array.from(new Set(this._rangePoints)).sort((a, b) =>
|
---|
35 | a < b ? -1 : 1
|
---|
36 | );
|
---|
37 | const parallelism = segments.map(() => 0);
|
---|
38 | const rangeStartIndices = [];
|
---|
39 | for (let i = 0; i < this._rangePoints.length; i += 2) {
|
---|
40 | const start = this._rangePoints[i];
|
---|
41 | const end = this._rangePoints[i + 1];
|
---|
42 | let idx = binarySearchBounds.eq(segments, start);
|
---|
43 | rangeStartIndices.push(idx);
|
---|
44 | do {
|
---|
45 | parallelism[idx]++;
|
---|
46 | idx++;
|
---|
47 | } while (segments[idx] < end);
|
---|
48 | }
|
---|
49 | for (let i = 0; i < this._rangeCallbacks.length; i++) {
|
---|
50 | const start = this._rangePoints[i * 2];
|
---|
51 | const end = this._rangePoints[i * 2 + 1];
|
---|
52 | let idx = rangeStartIndices[i];
|
---|
53 | let sum = 0;
|
---|
54 | let totalDuration = 0;
|
---|
55 | let current = start;
|
---|
56 | do {
|
---|
57 | const p = parallelism[idx];
|
---|
58 | idx++;
|
---|
59 | const duration = segments[idx] - current;
|
---|
60 | totalDuration += duration;
|
---|
61 | current = segments[idx];
|
---|
62 | sum += p * duration;
|
---|
63 | } while (current < end);
|
---|
64 | this._rangeCallbacks[i](sum / totalDuration);
|
---|
65 | }
|
---|
66 | }
|
---|
67 | }
|
---|
68 |
|
---|
69 | module.exports = ParallelismFactorCalculator;
|
---|