123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import _ from 'lodash';
- import stringWidth from 'string-width';
- const alignments = [
- 'left',
- 'right',
- 'center'
- ];
- const alignLeft = (subject, width) => {
- return subject + ' '.repeat(width);
- };
- const alignRight = (subject, width) => {
- return ' '.repeat(width) + subject;
- };
- const alignCenter = (subject, width) => {
- let halfWidth;
- halfWidth = width / 2;
- if (halfWidth % 2 === 0) {
- return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth);
- } else {
- halfWidth = Math.floor(halfWidth);
- return ' '.repeat(halfWidth) + subject + ' '.repeat(halfWidth + 1);
- }
- };
- export default (subject, containerWidth, alignment) => {
- if (!_.isString(subject)) {
- throw new TypeError('Subject parameter value must be a string.');
- }
- if (!_.isNumber(containerWidth)) {
- throw new TypeError('Container width parameter value must be a number.');
- }
- const subjectWidth = stringWidth(subject);
- if (subjectWidth > containerWidth) {
-
- throw new Error('Subject parameter value width cannot be greater than the container width.');
- }
- if (!_.isString(alignment)) {
- throw new TypeError('Alignment parameter value must be a string.');
- }
- if (!alignments.includes(alignment)) {
- throw new Error('Alignment parameter value must be a known alignment parameter value (left, right, center).');
- }
- if (subjectWidth === 0) {
- return ' '.repeat(containerWidth);
- }
- const availableWidth = containerWidth - subjectWidth;
- if (alignment === 'left') {
- return alignLeft(subject, availableWidth);
- }
- if (alignment === 'right') {
- return alignRight(subject, availableWidth);
- }
- return alignCenter(subject, availableWidth);
- };
|