Actualizacion maquina principal
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / table / dist / alignString.js.flow
1 import _ from 'lodash';
2 import stringWidth from 'string-width';
3
4 const alignments = [
5   'left',
6   'right',
7   'center'
8 ];
9
10 /**
11  * @param {string} subject
12  * @param {number} width
13  * @returns {string}
14  */
15 const alignLeft = (subject, width) => {
16   return subject + ' '.repeat(width);
17 };
18
19 /**
20  * @param {string} subject
21  * @param {number} width
22  * @returns {string}
23  */
24 const alignRight = (subject, width) => {
25   return ' '.repeat(width) + subject;
26 };
27
28 /**
29  * @param {string} subject
30  * @param {number} width
31  * @returns {string}
32  */
33 const alignCenter = (subject, width) => {
34   let halfWidth;
35
36   halfWidth = width / 2;
37
38   if (halfWidth % 2 === 0) {
39     return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth);
40   } else {
41     halfWidth = Math.floor(halfWidth);
42
43     return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth + 1);
44   }
45 };
46
47 /**
48  * Pads a string to the left and/or right to position the subject
49  * text in a desired alignment within a container.
50  *
51  * @param {string} subject
52  * @param {number} containerWidth
53  * @param {string} alignment One of the valid options (left, right, center).
54  * @returns {string}
55  */
56 export default (subject, containerWidth, alignment) => {
57   if (!_.isString(subject)) {
58     throw new TypeError('Subject parameter value must be a string.');
59   }
60
61   if (!_.isNumber(containerWidth)) {
62     throw new TypeError('Container width parameter value must be a number.');
63   }
64
65   const subjectWidth = stringWidth(subject);
66
67   if (subjectWidth > containerWidth) {
68     // console.log('subjectWidth', subjectWidth, 'containerWidth', containerWidth, 'subject', subject);
69
70     throw new Error('Subject parameter value width cannot be greater than the container width.');
71   }
72
73   if (!_.isString(alignment)) {
74     throw new TypeError('Alignment parameter value must be a string.');
75   }
76
77   if (!alignments.includes(alignment)) {
78     throw new Error('Alignment parameter value must be a known alignment parameter value (left, right, center).');
79   }
80
81   if (subjectWidth === 0) {
82     return ' '.repeat(containerWidth);
83   }
84
85   const availableWidth = containerWidth - subjectWidth;
86
87   if (alignment === 'left') {
88     return alignLeft(subject, availableWidth);
89   }
90
91   if (alignment === 'right') {
92     return alignRight(subject, availableWidth);
93   }
94
95   return alignCenter(subject, availableWidth);
96 };