1 import _ from 'lodash';
2 import stringWidth from 'string-width';
11 * @param {string} subject
12 * @param {number} width
15 const alignLeft = (subject, width) => {
16 return subject + ' '.repeat(width);
20 * @param {string} subject
21 * @param {number} width
24 const alignRight = (subject, width) => {
25 return ' '.repeat(width) + subject;
29 * @param {string} subject
30 * @param {number} width
33 const alignCenter = (subject, width) => {
36 halfWidth = width / 2;
38 if (halfWidth % 2 === 0) {
39 return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth);
41 halfWidth = Math.floor(halfWidth);
43 return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth + 1);
48 * Pads a string to the left and/or right to position the subject
49 * text in a desired alignment within a container.
51 * @param {string} subject
52 * @param {number} containerWidth
53 * @param {string} alignment One of the valid options (left, right, center).
56 export default (subject, containerWidth, alignment) => {
57 if (!_.isString(subject)) {
58 throw new TypeError('Subject parameter value must be a string.');
61 if (!_.isNumber(containerWidth)) {
62 throw new TypeError('Container width parameter value must be a number.');
65 const subjectWidth = stringWidth(subject);
67 if (subjectWidth > containerWidth) {
68 // console.log('subjectWidth', subjectWidth, 'containerWidth', containerWidth, 'subject', subject);
70 throw new Error('Subject parameter value width cannot be greater than the container width.');
73 if (!_.isString(alignment)) {
74 throw new TypeError('Alignment parameter value must be a string.');
77 if (!alignments.includes(alignment)) {
78 throw new Error('Alignment parameter value must be a known alignment parameter value (left, right, center).');
81 if (subjectWidth === 0) {
82 return ' '.repeat(containerWidth);
85 const availableWidth = containerWidth - subjectWidth;
87 if (alignment === 'left') {
88 return alignLeft(subject, availableWidth);
91 if (alignment === 'right') {
92 return alignRight(subject, availableWidth);
95 return alignCenter(subject, availableWidth);