All files / src/utils code-block.ts

100% Statements 30/30
100% Branches 11/11
100% Functions 1/1
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 311x 1x 1x 1x 1x 1x 13x 1x 1x 12x 12x 12x 12x 12x 12x 13x 13x 13x 13x 13x 13x 13x 13x 10x 10x 2x 2x 12x 12x 12x  
/**
 * Removes leading and trailing whitespace from a code block string.
 * @param code - The code block string to process.
 * @returns The processed code block string.
 */
export function codeBlock(code: string): string {
  if (!code) {
    throw new Error('Input string cannot be empty');
  }
 
  // Remove the new line at the start of the code
  const newCode = code.replace(/^\n/, '');
 
  // Get the whitespace from the first line
  const match = newCode.match(/^(\s+)/);
  const whitespace = match ? match[1] : '';
 
  // Decrease code indentation by the length of the whitespace from the first line
  const lines = newCode.split('\n').map((s) => s.replace(whitespace, ''));
 
  // Remove all whitespace from the last line
  const lastLine = lines.at(-1)?.replaceAll(/\s/g, '');
  if (lastLine?.length === 0) {
    lines[lines.length - 1] = '';
  } else {
    lines.push('');
  }
 
  return lines.join('\n');
}