DEV Community

Discussion on: How would you refactor this JS function?

Collapse
 
rkallan profile image
RRKallan

There is a small bug in your last solution

const isEmpty = (line) => line !== '' && line != null;
Enter fullscreen mode Exit fullscreen mode

returns false when line = "" and true when line = "test"

possible solution

const isEmpty = (line) => !line && line !== 0;
const isFirstLine = (index) => !index;
const getElementTag = (index) => (isFirstLine(index) ? "h1" : "p");
const getText = (line, index) => {
    const elementTag = getElementTag(index);
    const text = `<${elementTag}>${line}</${elementTag}>`;
    return text;
};
const br = () => "<br />";
const lineChecker = (line = "", index) => {
    if (isEmpty(line)) return br();

    return getText(line, index);
};

const checkLines = (lines = []) => lines.map(lineChecker);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
whatthehanan profile image
Hanan Hamza

the easiest way to check for all falsy values would be if(!!line === false)

Thread Thread
 
rkallan profile image
RRKallan

What do you think about?

If(!line)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nombrekeff profile image
Keff

Ohh my bad. Thanks for pointing it out! I did not run the code after the refactor (big mistake when refactoring)

Thread Thread
 
rkallan profile image
RRKallan

haha can happen :)

Thread Thread
 
nombrekeff profile image
Keff

It definitely does, I've been away from javascript for a while, mostly working with dart/flutter...