histogramHelper.js 2.3 KB
Newer Older
B
BingBlog 已提交
1 2
import {min, max, range} from 'lodash';

3
export function tansformBackendData(histogramData) {
4
    let [time, step, items] = histogramData;
B
BingBlog 已提交
5 6 7 8 9
    return {
        time,
        step,
        min: min(items.map(([left, right, count]) => left)),
        max: max(items.map(([left, right, count]) => right)),
10
        items: items.map(([left, right, count]) => ({left, right, count})),
B
BingBlog 已提交
11
    };
12
}
B
BingBlog 已提交
13

14
export function computeNewHistogram(histogram, min, max, binsNum = 30) {
B
BingBlog 已提交
15 16 17 18 19
    if (max === min) {
        // Create bins even if all the data has a single value.
        max = min * 1.1 + 1;
        min = min / 1.1 - 1;
    }
20 21
    let stepWidth = (max - min) / binsNum;
    let itemIndex = 0;
22
    return range(min, max, stepWidth).map((binLeft) => {
23
        let binRight = binLeft + stepWidth;
B
BingBlog 已提交
24
        let yValue = 0;
25 26 27 28 29 30 31 32 33 34
        while (itemIndex < histogram.items.length) {
            let itemRight = Math.min(max, histogram.items[itemIndex].right);
            let itemLeft = Math.max(min, histogram.items[itemIndex].left);
            let overlap = Math.min(itemRight, binRight) - Math.max(itemLeft, binLeft);
            let count = (overlap / (itemRight - itemLeft)) * histogram.items[itemIndex].count;
            yValue += overlap > 0 ? count : 0;
            // If `itemRight` is bigger than `binRight`, then this bin is
            // finished and there also has data for the next bin, so don't increment
            // `itemIndex`.
            if (itemRight > binRight) {
B
BingBlog 已提交
35 36
                break;
            }
37
            itemIndex++;
B
BingBlog 已提交
38
        }
39
        return {x: binLeft, dx: stepWidth, y: yValue};
B
BingBlog 已提交
40
    });
41
}
B
BingBlog 已提交
42

43
export function tansformToVisData(tempData, time, step) {
44
    return tempData.map(function(dataItem) {
45 46 47
        return [time, step, dataItem.x + dataItem.dx / 2, Math.floor(dataItem.y)];
    });
}
B
BingBlog 已提交
48

49 50 51 52
export function originDataToChartData(originData) {
    let tempData = originData.map(tansformBackendData);
    let globalMin = min(tempData.map(({min}) => min));
    let globalMax = max(tempData.map(({max}) => max));
53
    let chartData = tempData.map(function(item) {
54
        let histoBins = computeNewHistogram(item, globalMin, globalMax);
B
BingBlog 已提交
55 56 57 58
        let {time, step} = item;
        return {
            time,
            step,
59
            items: tansformToVisData(histoBins, time, step),
B
BingBlog 已提交
60 61 62
        };
    });
    return {
63 64
        min: globalMin,
        max: globalMax,
65
        chartData,
B
BingBlog 已提交
66
    };
67
}