All files / src spaceTrimSimple.ts

100% Statements 22/22
100% Branches 1/1
100% Functions 5/5
100% Lines 16/16

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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 493x                 3x   22x       22x   22x 47x   40x 40x   40x     22x 4x     18x   40x                   18x 43x     18x    
import { verticalTrim } from './verticalTrim';
 
/**
 * Trims string from all 4 sides
 *
 * Note: `spaceTrimSimple` does not support nested blocks, `spaceTrim` does
 *
 * @private withing the repository
 */
export function spaceTrimSimple(content: string): string {
    // ✂️ Trimming from top and bottom
    content = verticalTrim(content);
 
    // ✂️ Trimming from left and right
 
    const lines = content.split('\n');
 
    const lineStats = lines
        .filter((line) => line.trim() !== '')
        .map((line) => {
            const contentStart = line.length - line.trimStart().length;
            const contentEnd = contentStart + line.trim().length;
 
            return { contentStart, contentEnd };
        });
 
    if (lineStats.length === 0) {
        return '';
    }
 
    const { minContentStart, maxContentEnd } = lineStats.reduce(
        // tslint:disable-next-line: no-shadowed-variable
        ({ minContentStart, maxContentEnd }, { contentStart, contentEnd }) => ({
            minContentStart: Math.min(minContentStart, contentStart),
            maxContentEnd: Math.max(maxContentEnd, contentEnd),
        }),
        {
            minContentStart: lineStats[0].contentStart,
            maxContentEnd: lineStats[0].contentEnd,
        },
    );
 
    const horizontalyTrimmedLines = lines.map((line) =>
        line.substring(minContentStart, maxContentEnd),
    );
 
    return horizontalyTrimmedLines.join('\n');
}