summaryrefslogtreecommitdiff
path: root/src/utilities/_sila/metricProperties.js
blob: e435bab2d9a0a6fb38aeaf6a0be54d94efe0bd30 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
export function getGroups(data) {
  return Object.keys(
    data.reduce(function (rv, x) {
      (rv[x['Sensor']] = rv[x['Sensor']] || []).push(x);
      return rv;
    }, {})
  );
}

export function getItems(data, float = false) {
  let filteredData = data.filter((metric) => {
    return metric.Value !== 'nan';
  });

  let transform = filteredData.map((metric) => {
    let date = new Date(metric.Timestamp);
    return {
      ...metric,
      Timestamp: {
        time:
          date.getHours() + ':' + String(date.getMinutes()).padStart(2, '0'),
        date: formatDate(date),
      },
      Value: float ? metric.Value : Math.round(metric.Value),
    };
  });

  let group = transform.reduce(function (rv, x) {
    (rv[x['Sensor']] = rv[x['Sensor']] || []).push(x);
    return rv;
  }, {});
  return Object.keys(group).map((metric) => {
    return {
      name: metric,
      current: group[metric][group[metric].length - 1].Value,
      middle: findAverage(group[metric]),
      min: findMin(group[metric]),
      minDate: findDateOfMin(group[metric]),
      max: findMax(group[metric]),
      maxDate: findDateOfMax(group[metric]),
    };
  });
}

function padTo2Digits(num) {
  return num.toString().padStart(2, '0');
}

function formatDate(date) {
  return [
    padTo2Digits(date.getDate()),
    padTo2Digits(date.getMonth() + 1),
    date.getFullYear(),
  ].join('.');
}

function findAverage(arr) {
  const { length } = arr;
  return Math.round(
    arr.reduce((acc, val) => {
      return acc + val.Value / length;
    }, 0)
  );
}

function findMin(arr) {
  return arr.reduce((min, p) => (p.Value < min ? p.Value : min), arr[0].Value);
}

function findMax(arr) {
  return arr.reduce((max, p) => (p.Value > max ? p.Value : max), arr[0].Value);
}

function findDateOfMin(arr) {
  return arr.reduce((res, obj) => (obj.Value < res.Value ? obj : res))
    .Timestamp;
}

function findDateOfMax(arr) {
  return arr.reduce((res, obj) => (obj.Value > res.Value ? obj : res))
    .Timestamp;
}