1 | const utils = require('./utils')
|
2 | const { PAD, verifyData, maxKeyLen, EOL } = utils
|
3 |
|
4 | module.exports = (data, opts) => {
|
5 | verifyData(data)
|
6 |
|
7 | const newOpts = Object.assign({
|
8 | barWidth: 1,
|
9 | style: '*',
|
10 | left: 1,
|
11 | width: 10,
|
12 | padding: 1
|
13 | }, opts)
|
14 |
|
15 | const {
|
16 | barWidth, left, width,
|
17 | padding, style
|
18 | } = newOpts
|
19 |
|
20 | let result = PAD.repeat(left)
|
21 |
|
22 | const values = data.map(item => item.value)
|
23 | const max = Math.max.apply(null, values)
|
24 | const maxKeyLength = maxKeyLen(data)
|
25 |
|
26 | let tmp, padChar, ratioLength, key, line
|
27 | const valLength = values.length
|
28 | for (let i = 0; i < valLength; i++) {
|
29 | tmp = data[i]
|
30 | ratioLength = Math.round(width * (tmp.value / max))
|
31 | padChar = tmp.style ? tmp.style : style
|
32 | key = tmp.key
|
33 | line = padChar.repeat(ratioLength) + EOL + PAD.repeat(left)
|
34 | result += key.padStart(maxKeyLength) + PAD
|
35 |
|
36 | for (let j = 0; j < (tmp.barWidth || barWidth); j++) {
|
37 | if (j > 0) {
|
38 | result += PAD.repeat(maxKeyLength + 1) + line
|
39 | } else {
|
40 | result += line
|
41 | }
|
42 | }
|
43 |
|
44 | if (i !== valLength - 1) {
|
45 | result += EOL.repeat(padding) + PAD.repeat(left)
|
46 | }
|
47 | }
|
48 |
|
49 | return result
|
50 | }
|