DEV Community

Discussion on: How would you refactor this JS function?

Collapse
 
moopet profile image
Ben Sinclair • Edited

I'd address two problems:

I don't know what this function does

lineChecker doesn't tell me what it's checking, or what a "line" is, for that matter. I can guess it's a single line from some text based on the contents of the function, but...

This function doesn't do what it says

This function returns a formatted string based on the current line. It's producing output, not checking something. I'd expect a "check" function to return some meta information or a boolean regarding the passed data's validity.

As far as refactoring goes, there's no point in defining the document variable at all, and its name is misleading - it's a single HTML element as a string. "Document" is a word we associate with the DOM or, well, entire documents.

The last else if is redundant, it's the same as an else there.

I'd probably do this, but I'm not overjoyed about it:


javascript
formatLineAsHtmlFragment(line, isFirstLine) {
  if (line === "") {
    return "<br>";
  }

  if (isFirstLine) {
    return `<h1>${line}</h1>`;
  }

  return `<p>${line}</p>`;
}

EDIT: why is my code not formatted as javascript when I did the backtick dance?
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lgrammel profile image
Lars Grammel P42

Triple-backtick javascript worked for me to get JS formatting.

Collapse
 
moopet profile image
Ben Sinclair

I just changed it to that and it still breaketh!

Thread Thread
 
lgrammel profile image
Lars Grammel P42

javascript needs to be immediately after the 3 backticks, and needs to be followed by a newline.

Thread Thread
 
moopet profile image
Ben Sinclair

It is, and it's exactly how I've done it in all my other posts where it works fine. I'm not sure what's wrong with this one. Anyway, people can imagine what it's like with colours :)