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

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

14
export const 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 22 23
    let stepWidth = (max - min) / binsNum;
    let itemIndex = 0;
    return range(min, max, stepWidth).map(binLeft => {
        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 42
    });
};

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

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