forked from max-mapper/datop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chart.js
100 lines (80 loc) · 2.45 KB
/
chart.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var Drawille = require('drawille')
var prettybytes = require('pretty-bytes')
module.exports.create = function(box) {
var width = (box.width - 3) * 2
var height = (box.height - 2) * 4
var canvas = new Drawille(width, height)
var values = []
var chart = {
chart: canvas,
values: values,
width: width,
height: height,
ready: false,
min: 0,
max: 0
}
return chart
}
module.exports.resize = function(chart, box) {
var width = (box.width - 3) * 2
var height = (box.height - 2) * 4
chart.chart = new Drawille(width, height)
chart.width = width
chart.height = height
}
module.exports.draw = function(chart, position) {
var c = chart.chart
c.clear()
if (!chart.ready) {
return false
}
var dataPointsToKeep = 1000
chart.values[position] = chart.value
if (position > dataPointsToKeep) {
delete chart.values[position - dataPointsToKeep]
}
chart.min = 0
chart.max = 0 // 1kb
chart.average = 0
var avgCount = 0
// do first pass to determine min/max
for (var i = 0; i < chart.width; i++) {
var rawval = chart.values[chart.values.length - i]
if (rawval > 0) {
avgCount++
chart.average += rawval
if (rawval < chart.min) chart.min = rawval
if (rawval > chart.max) chart.max = rawval
}
}
chart.average = ~~(chart.average / avgCount)
for (var pos in chart.values) {
var p = parseInt(pos, 10) + (chart.width - chart.values.length)
var pval = computeValue(chart.values[pos])
if (p > 0 && chart.values[pos] > 0) {
c.set(p, chart.height - 1)
}
for (var y = 0; y < pval; y++) {
c.set(p, chart.height - y)
}
}
// Add percentage to top right of the chart by splicing it into the braille data
var textOutput = c.frame().split("\n")
var currentVal = prettybytes(chart.values[chart.values.length - 1])
var msg = "current: " + currentVal + ", avg: " + prettybytes(chart.average) + ', max: ' + prettybytes(chart.max)
textOutput[0] = textOutput[0].slice(0, textOutput[0].length - msg.length) + msg
return textOutput.join("\n")
function computeValue(input) {
var max = chart.max
if (max < 1000) max = 1000
return ~~scale(input, chart.min, max, 0, chart.height)
}
}
function scale( x, fromLow, fromHigh, toLow, toHigh ) {
return ( x - fromLow ) * ( toHigh - toLow ) / ( fromHigh - fromLow ) + toLow
}
function stringRepeat(string, num) {
if (num < 0) return ''
return new Array(num + 1).join(string)
}