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

3
export function tansformBackendData(histogramData) {
J
Jeff Wang 已提交
4 5 6 7 8 9 10 11
  let [time, step, items] = histogramData;
  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})),
  };
12
}
B
BingBlog 已提交
13

14
export function computeNewHistogram(histogram, min, max, binsNum = 30) {
J
Jeff Wang 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
  if (max === min) {
    // Create bins even if all the data has a single value.
    max = min * 1.1 + 1;
    min = min / 1.1 - 1;
  }
  let stepWidth = (max - min) / binsNum;
  let itemIndex = 0;
  return range(min, max, stepWidth).map((binLeft) => {
    let binRight = binLeft + stepWidth;
    let yValue = 0;
    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) {
        break;
      }
      itemIndex++;
B
BingBlog 已提交
38
    }
J
Jeff Wang 已提交
39 40
    return {x: binLeft, dx: stepWidth, y: yValue};
  });
41
}
B
BingBlog 已提交
42

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

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