-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
81 lines (64 loc) · 1.25 KB
/
index.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
/**
* Module dependencies.
*/
var chart = require('chart');
/**
* Return a histogram with `data`.
*
* @param {Array} data
* @param {Object} [opts]
* @return {String}
* @api public
*/
module.exports = function(data, opts){
var opts = opts || {};
var bins = opts.bins || 50;
data = bin(data, bins, opts);
return chart(data);
};
/**
* Bin `data` into `total` bins.
*
* @param {Array} data
* @param {Number} total
* @param {Object} options
* @return {Array}
* @api public
*/
function bin(data, total, opts){
opts = opts || {};
var mi = null == opts.min ? min(data) : opts.min;
var ma = null == opts.max ? max(data) : opts.max;
var delta = ma - mi;
// initialize bins
var bins = [];
for (var i = 0; i < total; i++) bins[i] = 0;
// distribute
for (var i = 0; i < data.length; i++) {
var n = data[i];
var p = (n - mi) / (ma - mi);
var b = Math.max(0, (total * p | 0) - 1);
bins[b]++;
}
return bins;
};
/**
* Min of `arr`.
*/
function min(arr) {
var n = arr[0];
for (var i = 1; i < arr.length; i++) {
n = arr[i] < n ? arr[i] : n;
}
return n;
}
/**
* Max of `arr`.
*/
function max(arr) {
var n = arr[0];
for (var i = 1; i < arr.length; i++) {
n = arr[i] > n ? arr[i] : n;
}
return n;
}