UNPKG

2.21 kBJavaScriptView Raw
1"use strict";
2var __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");
9const alignLeft = (subject, width) => {
10 return subject + ' '.repeat(width);
11};
12const alignRight = (subject, width) => {
13 return ' '.repeat(width) + subject;
14};
15const alignCenter = (subject, width) => {
16 return ' '.repeat(Math.floor(width / 2)) + subject + ' '.repeat(Math.ceil(width / 2));
17};
18const alignJustify = (subject, width) => {
19 const spaceSequenceCount = (0, utils_1.countSpaceSequence)(subject);
20 if (spaceSequenceCount === 0) {
21 return alignLeft(subject, width);
22 }
23 const addingSpaces = (0, 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 });
31};
32/**
33 * Pads a string to the left and/or right to position the subject
34 * text in a desired alignment within a container.
35 */
36const alignString = (subject, containerWidth, alignment) => {
37 const subjectWidth = (0, 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);
58};
59exports.alignString = alignString;
60//# sourceMappingURL=alignString.js.map
\No newline at end of file