DEV Community

Discussion on: How would you refactor this JS function?

Collapse
 
pawelmiczka profile image
Paweł Miczka
function lineChecker(line: string, isFirstLine: boolean) {
    if (line === '') return '<br />';

    return {
        [0]: `<p>${line}</p>`,
        [1]: `<h1>${line}</h1>`
    }[Number(isFirstLine)]
}
Enter fullscreen mode Exit fullscreen mode

but for that I would probably try to style it with CSS using ::first-line

Collapse
 
pawelmiczka profile image
Paweł Miczka

it is possible to use array too

function lineChecker(line: string, isFirstLine: boolean) {
    if (line === '') return '<br />';

    return [
        `<p>${line}</p>`, 
        `<h1>${line}</h1>`
    ][Number(isFirstLine)];
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pawelmiczka profile image
Paweł Miczka

and yet another idea - use markdown cause why not?