align.js
1.39 KB
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
'use strict'
var stringWidth = require('string-width')
exports.center = alignCenter
exports.left = alignLeft
exports.right = alignRight
// lodash's way of generating pad characters.
function createPadding (width) {
var result = ''
var string = ' '
var n = width
do {
if (n % 2) {
result += string;
}
n = Math.floor(n / 2);
string += string;
} while (n);
return result;
}
function alignLeft (str, width) {
var trimmed = str.trimRight()
if (trimmed.length === 0 && str.length >= width) return str
var padding = ''
var strWidth = stringWidth(trimmed)
if (strWidth < width) {
padding = createPadding(width - strWidth)
}
return trimmed + padding
}
function alignRight (str, width) {
var trimmed = str.trimLeft()
if (trimmed.length === 0 && str.length >= width) return str
var padding = ''
var strWidth = stringWidth(trimmed)
if (strWidth < width) {
padding = createPadding(width - strWidth)
}
return padding + trimmed
}
function alignCenter (str, width) {
var trimmed = str.trim()
if (trimmed.length === 0 && str.length >= width) return str
var padLeft = ''
var padRight = ''
var strWidth = stringWidth(trimmed)
if (strWidth < width) {
var padLeftBy = parseInt((width - strWidth) / 2, 10)
padLeft = createPadding(padLeftBy)
padRight = createPadding(width - (strWidth + padLeftBy))
}
return padLeft + trimmed + padRight
}