1 | const utils = require('./utils')
|
2 | const { PAD, padMid, verifyData, EOL } = utils
|
3 |
|
4 | module.exports = (data, opts) => {
|
5 | verifyData(data)
|
6 |
|
7 | const newOpts = Object.assign({
|
8 | barWidth: 3,
|
9 | left: 1,
|
10 | height: 6,
|
11 | padding: 3,
|
12 | style: '*'
|
13 | }, opts)
|
14 |
|
15 | const {
|
16 | barWidth, left, height,
|
17 | padding, style
|
18 | } = newOpts
|
19 | let result = PAD.repeat(left)
|
20 |
|
21 | const values = data.map(item => item.value)
|
22 | const max = Math.max.apply(null, values)
|
23 | const length = data.length
|
24 |
|
25 | let tmp, padChar, ratio, valStr
|
26 | for (let i = 0; i < height + 2; i++) {
|
27 | for (let j = 0; j < length; j++) {
|
28 | tmp = data[j]
|
29 | valStr = tmp.value.toString()
|
30 | ratio = height - (height * tmp.value / max)
|
31 |
|
32 |
|
33 | padChar = ratio > (i + 2) ? PAD
|
34 | : Math.round(ratio) === i
|
35 | ? valStr
|
36 | : Math.round(ratio) < i
|
37 | ? (tmp.style || style) : PAD
|
38 |
|
39 | if (padChar === valStr) {
|
40 | result += padMid(valStr, barWidth) + PAD.repeat(padding)
|
41 | continue
|
42 | }
|
43 |
|
44 | if (i !== height + 1) {
|
45 |
|
46 |
|
47 |
|
48 | result += padChar.repeat(barWidth)
|
49 |
|
50 |
|
51 | result += PAD.repeat(padding)
|
52 | } else {
|
53 | result += tmp.key.length > barWidth
|
54 | ? tmp.key.padEnd(barWidth + padding)
|
55 | : padMid(tmp.key, barWidth) + PAD.repeat(padding)
|
56 | }
|
57 | }
|
58 |
|
59 | if (i !== height + 1) {
|
60 | result += EOL + PAD.repeat(left)
|
61 | }
|
62 | }
|
63 |
|
64 | return result
|
65 | }
|