-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (65 loc) · 1.77 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
// Import Third-party Dependencies
import wcwidth from "@topcli/wcwidth";
/**
* @function left
* @description Align string on the left
* @param {!string} str
* @param {!number} width
* @returns {string}
*
* @example
* const align = require("@slimio/text-align");
* console.log(align.left("boo", 5)); // "boo ";
*/
export function left(str, width) {
const trimmed = str.trimEnd();
if (trimmed.length === 0 && str.length >= width) {
return str;
}
const strWidth = wcwidth(trimmed);
return trimmed + (strWidth < width ? "".padEnd(width - strWidth) : "");
}
/**
* @function right
* @description Align string on the right
* @param {!string} str
* @param {!number} width
* @returns {string}
*
* @example
* const align = require("@slimio/text-align");
* console.log(align.right("boo", 5)); // " boo";
*/
export function right(str, width) {
const trimmed = str.trimStart();
if (trimmed.length === 0 && str.length >= width) {
return str;
}
const strWidth = wcwidth(trimmed);
return (strWidth < width ? "".padStart(width - strWidth) : "") + trimmed;
}
/**
* @function center
* @description Align string at the center
* @param {!string} str
* @param {!number} width
* @returns {string}
*
* @example
* const align = require("@slimio/text-align");
* console.log(align.center("boo", 5)); // " boo ";
*/
export function center(str, width) {
const trimmed = str.trim();
if (trimmed.length === 0 && str.length >= width) {
return str;
}
const strWidth = wcwidth(trimmed);
let [padLeft, padRight] = ["", ""];
if (strWidth < width) {
const padLeftBy = parseInt((width - strWidth) / 2, 10);
padLeft = padLeft.padEnd(padLeftBy);
padRight = padRight.padStart(width - (strWidth + padLeftBy));
}
return padLeft + trimmed + padRight;
}