blob: 61dc552c948a989d447b0ce2b2aac70d496227a0 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001"use strict";
Tim van der Lippe38208902021-05-11 16:37:59 +01002var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.alignString = void 0;
7const string_width_1 = __importDefault(require("string-width"));
8const utils_1 = require("./utils");
Yang Guo4fd355c2019-09-19 10:59:03 +02009const alignLeft = (subject, width) => {
Tim van der Lippe38208902021-05-11 16:37:59 +010010 return subject + ' '.repeat(width);
Yang Guo4fd355c2019-09-19 10:59:03 +020011};
Yang Guo4fd355c2019-09-19 10:59:03 +020012const alignRight = (subject, width) => {
Tim van der Lippe38208902021-05-11 16:37:59 +010013 return ' '.repeat(width) + subject;
Yang Guo4fd355c2019-09-19 10:59:03 +020014};
Yang Guo4fd355c2019-09-19 10:59:03 +020015const alignCenter = (subject, width) => {
Tim van der Lippe38208902021-05-11 16:37:59 +010016 return ' '.repeat(Math.floor(width / 2)) + subject + ' '.repeat(Math.ceil(width / 2));
17};
18const alignJustify = (subject, width) => {
19 const spaceSequenceCount = utils_1.countSpaceSequence(subject);
20 if (spaceSequenceCount === 0) {
21 return alignLeft(subject, width);
22 }
23 const addingSpaces = utils_1.distributeUnevenly(width, spaceSequenceCount);
24 if (Math.max(...addingSpaces) > 3) {
25 return alignLeft(subject, width);
26 }
27 let spaceSequenceIndex = 0;
28 return subject.replace(/\s+/g, (groupSpace) => {
29 return groupSpace + ' '.repeat(addingSpaces[spaceSequenceIndex++]);
30 });
Yang Guo4fd355c2019-09-19 10:59:03 +020031};
32/**
33 * Pads a string to the left and/or right to position the subject
34 * text in a desired alignment within a container.
Yang Guo4fd355c2019-09-19 10:59:03 +020035 */
Yang Guo4fd355c2019-09-19 10:59:03 +020036const alignString = (subject, containerWidth, alignment) => {
Tim van der Lippe38208902021-05-11 16:37:59 +010037 const subjectWidth = string_width_1.default(subject);
38 if (subjectWidth === containerWidth) {
39 return subject;
40 }
41 if (subjectWidth > containerWidth) {
42 throw new Error('Subject parameter value width cannot be greater than the container width.');
43 }
44 if (subjectWidth === 0) {
45 return ' '.repeat(containerWidth);
46 }
47 const availableWidth = containerWidth - subjectWidth;
48 if (alignment === 'left') {
49 return alignLeft(subject, availableWidth);
50 }
51 if (alignment === 'right') {
52 return alignRight(subject, availableWidth);
53 }
54 if (alignment === 'justify') {
55 return alignJustify(subject, availableWidth);
56 }
57 return alignCenter(subject, availableWidth);
Yang Guo4fd355c2019-09-19 10:59:03 +020058};
Tim van der Lippe38208902021-05-11 16:37:59 +010059exports.alignString = alignString;