All files / src/helpers line-ending.helper.ts

100% Statements 55/55
100% Branches 14/14
100% Functions 4/4
100% Lines 55/55

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 49 50 51 52 53 54 55 561x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 1x 5x 1x 5x 1x 5x 1x 5x 1x 5x 5x 1x 1x 1x 1x 1x 16x 16x 16x 2x 2x 14x 16x 13x 13x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x  
import { EOL } from 'os';
 
export type LineEnding = 'LF' | 'CRLF' | 'CR' | 'LFCR';
export const lineEndings: LineEnding[] = ['LF', 'CRLF', 'CR', 'LFCR'];
 
const multiCharRegExp = /(\r\n)|(\n\r)/g;
const singleCharRegExp = /(\r)|(\n)/g;
 
// https://en.wikipedia.org/wiki/Newline
/**
 * returns escape sequence for given line ending
 * @param lineEnding
 */
export function getEscapeSequence(lineEnding: LineEnding): string {
    switch (lineEnding) {
        case 'CR':
            return '\r';
        case 'CRLF':
            return '\r\n';
        case 'LF':
            return '\n';
        case 'LFCR':
            return '\n\r';
        default:
            return handleNever(lineEnding);
    }
}
 
function handleNever(lineEnding: never): string {
    throw new Error(`Unknown line ending: '${lineEnding}'. Line Ending must be one of ${lineEndings.join(', ')}`);
}
 
export function findEscapeSequence(content: string): string {
    const multiCharMatch = multiCharRegExp.exec(content);
    if (multiCharMatch != null) {
        return multiCharMatch[0];
    }
    const singleCharMatch = singleCharRegExp.exec(content);
    if (singleCharMatch != null) {
        return singleCharMatch[0];
    }
    return EOL;
}
 
/**
 * Splits a string into an array of lines.
 * Handles any line endings including a file with a mixture of lineEndings
 *
 * @param content multi line string to be split
 */
export function splitContent(content: string): string[] {
    content = content.replace(multiCharRegExp, '\n');
    content = content.replace(singleCharRegExp, '\n');
    return content.split('\n');
}