UNPKG

2.04 kBJavaScriptView Raw
1function loaddata (callback) {
2 setTimeout(function () {
3 const dataElement = document.querySelector('#clinic-data')
4 const data = JSON.parse(dataElement.textContent)
5
6 callback(null, wrapData(data))
7 })
8}
9module.exports = loaddata
10
11function wrapData (data) {
12 return new Data(data.analysis, data.processStat)
13}
14
15// Construct data container
16class Data {
17 constructor (analysis, data) {
18 this.analysis = analysis
19 this.data = data
20
21 this.rawTimestamp = data.map((point) => point.timestamp)
22
23 this.cpu = data.map((point) => ({
24 x: new Date(point.timestamp),
25 y: [point.cpu * 100]
26 }))
27
28 this.delay = data.map((point) => ({
29 x: new Date(point.timestamp),
30 y: [point.delay]
31 }))
32
33 const MB = Math.pow(1024, 2)
34 this.memory = data.map((point) => ({
35 x: new Date(point.timestamp),
36 y: [
37 point.memory.rss / MB,
38 point.memory.heapTotal / MB,
39 point.memory.heapUsed / MB
40 ]
41 }))
42
43 this.handles = data.map((point) => ({
44 x: new Date(point.timestamp),
45 y: [point.handles]
46 }))
47 }
48
49 getPoints (time) {
50 const index = closestIndexByBinarySearch(
51 this.rawTimestamp, time.getTime()
52 )
53
54 return {
55 cpu: this.cpu[index],
56 delay: this.delay[index],
57 memory: this.memory[index],
58 handles: this.handles[index]
59 }
60 }
61}
62
63function closestIndexByBinarySearch (array, searchValue) {
64 let startIndex = 0
65 let endIndex = array.length - 1
66 let middleIndex = Math.floor((startIndex + endIndex) / 2)
67
68 // continue until there are no elements between start and end
69 while (endIndex - startIndex > 1) {
70 if (searchValue <= array[middleIndex]) {
71 endIndex = middleIndex
72 } else {
73 startIndex = middleIndex
74 }
75
76 middleIndex = Math.floor((startIndex + endIndex) / 2)
77 }
78
79 // startIndex and endIndex are now the two options, return
80 // the one that is closest.
81 if (array[endIndex] - searchValue <= searchValue - array[startIndex]) {
82 return endIndex
83 } else {
84 return startIndex
85 }
86}