Align Columns - freeCodeCamp

What is your hint or solution suggestion?

Link to the challenge:

Hi everyone,

I’ve been tackling the “Align Columns” challenge from Rosetta Code and wanted to share a JavaScript solution that dynamically aligns text across different columns based on a specified alignment (left, right, or center).

Here’s the formatText function that takes an array of strings as input and an alignment argument. This function handles cases where input text lines may or may not have trailing dollar characters. It also ensures that all columns share the same alignment, and any consecutive space characters adjacent to the end of lines are considered insignificant for the task.

The code is as follows:

/* jshint esversion: 6 */
function formatText(input, alignment) {
  const delimiter = '$';
  // Split the input into rows and fields
  const rows = input.map(line => line.split(delimiter));
  // Find the maximum number of columns across all rows
  const maxCols = Math.max(...rows.map(cols => cols.length));
  // Normalize rows to have the same number of columns
  const normalizedRows = rows.map(cols => {
    while (cols.length < maxCols) {
      cols.push('');
    }
    return cols;
  });
  // Calculate the maximum width for each column
  const colWidths = Array.from({ length: maxCols }, (_, i) => {
    return Math.max(...normalizedRows.map(row => row[i].length));
  });
  // Function to align fields within their column based on alignment argument
  const alignField = (field, width, align) => {
    switch (align) {
      case 'left':
        return field.padEnd(width, ' ');
      case 'right':
        return field.padStart(width, ' ');
      case 'center':
        const totalPadding = width - field.length;
        const leftPadding = Math.floor(totalPadding / 2);
        return ' '.repeat(leftPadding) + field + ' '.repeat(totalPadding - leftPadding);
    }
  };
  // Map through each row and align fields, then join them into a string
  const alignedRows = normalizedRows.map(row => {
    return row.map((field, idx) => alignField(field, colWidths[idx], alignment)).join(' ');
  });
  // Join all aligned rows with newline characters
  return alignedRows.join('\n');
}
// Sample text for testing
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.'
];
// Displaying aligned text for different alignments
console.log("Right Aligned:\n" + formatText(testText, 'right'));
console.log("\nLeft Aligned:\n" + formatText(testText, 'left'));
console.log("\nCenter Aligned:\n" + formatText(testText, 'center'));

This solution uses the padStart and padEnd methods for left and right alignment, and a combination of both for central alignment. It ensures that the number of columns is normalized across all lines and calculates the maximum width of each column to determine the necessary spacing.

I hope this helps anyone facing this challenge. Feel free to give it a try and share your feedback or your own solutions!

We don’t allow solution code to be posted.

I have blurred it, but unless a thread invites a discussion or asks a question, we usually delete the code.