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