| 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 {(value: 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 | * Processes the provided start.
|
|---|
| 22 | * @param {number} start range start
|
|---|
| 23 | * @param {number} end range end
|
|---|
| 24 | * @param {Callback} callback callback
|
|---|
| 25 | * @returns {void}
|
|---|
| 26 | */
|
|---|
| 27 | range(start, end, callback) {
|
|---|
| 28 | if (start === end) return callback(1);
|
|---|
| 29 | this._rangePoints.push(start);
|
|---|
| 30 | this._rangePoints.push(end);
|
|---|
| 31 | this._rangeCallbacks.push(callback);
|
|---|
| 32 | }
|
|---|
| 33 |
|
|---|
| 34 | calculate() {
|
|---|
| 35 | const segments = [...new Set(this._rangePoints)].sort((a, b) =>
|
|---|
| 36 | a < b ? -1 : 1
|
|---|
| 37 | );
|
|---|
| 38 | const parallelism = segments.map(() => 0);
|
|---|
| 39 | /** @type {number[]} */
|
|---|
| 40 | const rangeStartIndices = [];
|
|---|
| 41 | for (let i = 0; i < this._rangePoints.length; i += 2) {
|
|---|
| 42 | const start = this._rangePoints[i];
|
|---|
| 43 | const end = this._rangePoints[i + 1];
|
|---|
| 44 | let idx = binarySearchBounds.eq(segments, start);
|
|---|
| 45 | rangeStartIndices.push(idx);
|
|---|
| 46 | do {
|
|---|
| 47 | parallelism[idx]++;
|
|---|
| 48 | idx++;
|
|---|
| 49 | } while (segments[idx] < end);
|
|---|
| 50 | }
|
|---|
| 51 | for (let i = 0; i < this._rangeCallbacks.length; i++) {
|
|---|
| 52 | const start = this._rangePoints[i * 2];
|
|---|
| 53 | const end = this._rangePoints[i * 2 + 1];
|
|---|
| 54 | let idx = rangeStartIndices[i];
|
|---|
| 55 | let sum = 0;
|
|---|
| 56 | let totalDuration = 0;
|
|---|
| 57 | let current = start;
|
|---|
| 58 | do {
|
|---|
| 59 | const p = parallelism[idx];
|
|---|
| 60 | idx++;
|
|---|
| 61 | const duration = segments[idx] - current;
|
|---|
| 62 | totalDuration += duration;
|
|---|
| 63 | current = segments[idx];
|
|---|
| 64 | sum += p * duration;
|
|---|
| 65 | } while (current < end);
|
|---|
| 66 | this._rangeCallbacks[i](sum / totalDuration);
|
|---|
| 67 | }
|
|---|
| 68 | }
|
|---|
| 69 | }
|
|---|
| 70 |
|
|---|
| 71 | module.exports = ParallelismFactorCalculator;
|
|---|