# Rosetta Code Challenges - Align columns

### Tell us what’s happening:

formatText(testText, ‘right’) should produce text with columns justified to the right.
Failed:formatText(testText, ‘left’) should produce text with columns justified to the left.
Failed:formatText(testText, ‘center’) should produce text with columns justified to the center.

``````function formatText(textArray, alignment = 'left') {
if (!Array.isArray(textArray) || textArray.length === 0) {
throw new Error('Input should be a non-empty array of strings.');
}

const validAlignments = ['left', 'right', 'center'];
if (!validAlignments.includes(alignment)) {
throw new Error(`Invalid alignment. Choose from: \${validAlignments.join(', ')}`);
}

// Split each line into fields
const splitLines = textArray.map(line => line.split('\$'));

// Determine the maximum width of each column
const colWidths = splitLines[0].map((_, colIndex) =>
Math.max(...splitLines.map(line => (line[colIndex] || '').length))
);

// Function to justify text within a given width
const justify = (text, width, alignment) => {
const spaces = width - text.length;
switch (alignment) {
case 'right':
return ' '.repeat(spaces) + text;
case 'center':
const leftSpaces = Math.floor(spaces / 2);
const rightSpaces = spaces - leftSpaces;
return ' '.repeat(leftSpaces) + text + ' '.repeat(rightSpaces);
case 'left':
default:
return text + ' '.repeat(spaces);
}
};

// Build the aligned text
const alignedText = splitLines.map(line =>
line.map((field, colIndex) => justify(field || '', colWidths[colIndex], alignment)).join(' ')
);

return alignedText.join('\n');
}

// Example usage:
const testText = [
'Given\$a\$text\$file\$of\$many\$lines',
'where\$fields\$within\$a\$line\$',
'are\$delineated\$by\$a\$single\$"dollar"\$character',
'write\$a\$program',
'that\$aligns\$each\$column\$of\$fields',
'by\$ensuring\$that\$words\$in\$each\$',
'column\$are\$separated\$by\$at\$least\$one\$space.',
'Further,\$allow\$for\$each\$word\$in\$a\$column\$to\$be\$either\$left\$',
'justified,\$right\$justified',
'or\$center\$justified\$within\$its\$column.'
];

console.log(formatText(testText, 'left')),
console.log(formatText(testText, 'right')),
console.log(formatText(testText, 'center'));

``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0`