UNPKG

1.77 kBJavaScriptView Raw
1const os = require('os')
2const PAD = ' '
3const EOL = os.EOL
4
5const bgColors = {
6 'black': '40',
7 'red': '41',
8 'green': '42',
9 'yellow': '43',
10 'blue': '44',
11 'magenta': '45',
12 'cyan': '46',
13 'white': '47'
14}
15
16module.exports = {
17 PAD,
18 EOL,
19
20 bg: (color = 'cyan', length = 1) => {
21 const currentBg = bgColors[color]
22 if (typeof color !== 'string' || !currentBg) {
23 throw new TypeError(`Invalid backgroundColor: ${JSON.stringify(color)}`)
24 }
25
26 return '\x1b[' + currentBg + 'm' + PAD.repeat(length) + '\x1b[0m'
27 },
28
29 fg: (color = 'cyan', str) => {
30 const currentBg = bgColors[color]
31 if (typeof color !== 'string' || !currentBg) {
32 throw new TypeError(`Invalid foregroundColor: ${JSON.stringify(color)}`)
33 }
34
35 return '\x1b[' + parseInt(bgColors[color] - 10) + 'm' + str + '\x1b[0m'
36 },
37
38 padMid: (str, width) => {
39 const mid = Math.round((width - str.length) / 2)
40 const length = str.length
41
42 return length > width ? str.padEnd(width)
43 : PAD.repeat(mid) + str +
44 PAD.repeat(mid + ((mid * 2 + length) > width ? -1 : 0))
45 },
46
47 verifyData: (data) => {
48 const length = data.length
49
50 if (!Array.isArray(data) ||
51 length === 0 ||
52 !data.every(item => item.key && !Number.isNaN(item.value))
53 ) {
54 throw new TypeError(`Invalid data: ${JSON.stringify(data)}`)
55 }
56 },
57
58 maxKeyLen: (data) => Math.max.apply(null, data.map(item => item.key.length)),
59 // eslint-disable-next-line
60 getOriginLen: (str) => str.replace(/\x1b\[[0-9;]*m/g, '').length,
61
62 curForward: (step = 1) => `\x1b[${step}C`,
63 curUp: (step = 1) => `\x1b[${step}A`,
64 curDown: (step = 1) => `\x1b[${step}B`,
65 curBack: (step = 1) => `\x1b[${step}D`
66}