UNPKG

2.74 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8var _lodash = _interopRequireDefault(require("lodash"));
9
10var _stringWidth = _interopRequireDefault(require("string-width"));
11
12function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
14const alignments = ['left', 'right', 'center'];
15/**
16 * @param {string} subject
17 * @param {number} width
18 * @returns {string}
19 */
20
21const alignLeft = (subject, width) => {
22 return subject + ' '.repeat(width);
23};
24/**
25 * @param {string} subject
26 * @param {number} width
27 * @returns {string}
28 */
29
30
31const alignRight = (subject, width) => {
32 return ' '.repeat(width) + subject;
33};
34/**
35 * @param {string} subject
36 * @param {number} width
37 * @returns {string}
38 */
39
40
41const alignCenter = (subject, width) => {
42 let halfWidth;
43 halfWidth = width / 2;
44
45 if (halfWidth % 2 === 0) {
46 return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth);
47 } else {
48 halfWidth = Math.floor(halfWidth);
49 return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth + 1);
50 }
51};
52/**
53 * Pads a string to the left and/or right to position the subject
54 * text in a desired alignment within a container.
55 *
56 * @param {string} subject
57 * @param {number} containerWidth
58 * @param {string} alignment One of the valid options (left, right, center).
59 * @returns {string}
60 */
61
62
63const alignString = (subject, containerWidth, alignment) => {
64 if (!_lodash.default.isString(subject)) {
65 throw new TypeError('Subject parameter value must be a string.');
66 }
67
68 if (!_lodash.default.isNumber(containerWidth)) {
69 throw new TypeError('Container width parameter value must be a number.');
70 }
71
72 const subjectWidth = (0, _stringWidth.default)(subject);
73
74 if (subjectWidth > containerWidth) {
75 // console.log('subjectWidth', subjectWidth, 'containerWidth', containerWidth, 'subject', subject);
76 throw new Error('Subject parameter value width cannot be greater than the container width.');
77 }
78
79 if (!_lodash.default.isString(alignment)) {
80 throw new TypeError('Alignment parameter value must be a string.');
81 }
82
83 if (alignments.indexOf(alignment) === -1) {
84 throw new Error('Alignment parameter value must be a known alignment parameter value (left, right, center).');
85 }
86
87 if (subjectWidth === 0) {
88 return ' '.repeat(containerWidth);
89 }
90
91 const availableWidth = containerWidth - subjectWidth;
92
93 if (alignment === 'left') {
94 return alignLeft(subject, availableWidth);
95 }
96
97 if (alignment === 'right') {
98 return alignRight(subject, availableWidth);
99 }
100
101 return alignCenter(subject, availableWidth);
102};
103
104var _default = alignString;
105exports.default = _default;
106//# sourceMappingURL=alignString.js.map
\No newline at end of file