1 | "use strict";
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.default = void 0;
|
7 |
|
8 | var _lodash = _interopRequireDefault(require("lodash"));
|
9 |
|
10 | var _stringWidth = _interopRequireDefault(require("string-width"));
|
11 |
|
12 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
13 |
|
14 | const alignments = ['left', 'right', 'center'];
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | const alignLeft = (subject, width) => {
|
22 | return subject + ' '.repeat(width);
|
23 | };
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | const alignRight = (subject, width) => {
|
32 | return ' '.repeat(width) + subject;
|
33 | };
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | const 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 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 | const 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 |
|
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 |
|
104 | var _default = alignString;
|
105 | exports.default = _default;
|
106 |
|
\ | No newline at end of file |