1 import isNumber from 'is-number-object';
2 import isString from 'is-string';
3 import stringWidth from 'string-width';
12 * @param {string} subject
13 * @param {number} width
16 const alignLeft = (subject, width) => {
17 return subject + ' '.repeat(width);
21 * @param {string} subject
22 * @param {number} width
25 const alignRight = (subject, width) => {
26 return ' '.repeat(width) + subject;
30 * @param {string} subject
31 * @param {number} width
34 const alignCenter = (subject, width) => {
37 halfWidth = width / 2;
39 if (width % 2 === 0) {
40 return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth);
42 halfWidth = Math.floor(halfWidth);
44 return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth + 1);
49 * Pads a string to the left and/or right to position the subject
50 * text in a desired alignment within a container.
52 * @param {string} subject
53 * @param {number} containerWidth
54 * @param {string} alignment One of the valid options (left, right, center).
57 export default (subject, containerWidth, alignment) => {
58 if (!isString(subject)) {
59 throw new TypeError('Subject parameter value must be a string.');
62 if (!isNumber(containerWidth)) {
63 throw new TypeError('Container width parameter value must be a number.');
66 const subjectWidth = stringWidth(subject);
68 if (subjectWidth > containerWidth) {
69 // console.log('subjectWidth', subjectWidth, 'containerWidth', containerWidth, 'subject', subject);
71 throw new Error('Subject parameter value width cannot be greater than the container width.');
74 if (!isString(alignment)) {
75 throw new TypeError('Alignment parameter value must be a string.');
78 if (!alignments.includes(alignment)) {
79 throw new Error('Alignment parameter value must be a known alignment parameter value (left, right, center).');
82 if (subjectWidth === 0) {
83 return ' '.repeat(containerWidth);
86 const availableWidth = containerWidth - subjectWidth;
88 if (alignment === 'left') {
89 return alignLeft(subject, availableWidth);
92 if (alignment === 'right') {
93 return alignRight(subject, availableWidth);
96 return alignCenter(subject, availableWidth);