During the weekend, I found the following small JS function in a blog post:
const lineChecker = (line, isFirstLine) => {
let document = ``;
if (line !== "" && isFirstLine) {
document += `<h1>${line}</h1>`;
} else if (line !== "" && !isFirstLine) {
document += `<p>${line}</p>`;
} else if (line === "") {
document += "<br />";
}
return document;
};
I refactored it and was thinking that it could be an excellent beginner-level refactoring kata.
How would you refactor it?
Latest comments (93)
Personally I'd do..
Leaving out all further context, this might be one of the rare occasions where to make use
!!(double ! operator)Note: After looking through some other solutions, I figured using
!!introduces (or solves? I wouldn't know) a problem when passing unexpected falsy - values such asnull,falseorundefined.I'd still say it's a pretty good example for refactoring. Even though it seems fairly easy to overengineer if you adhere to the 'functions do a single thing' mantra.
I have refactored like below. Divided all conditions to Spec Units and Grouped Spec Units. Check my Github Link to see my code.
github.com/SenthilKumaranC/How-To-...
One-liner:
functional implementation with ramda
Here's my one-liner that includes a hilarious immediately-invoked arrow function:
const lineChecker = (Line,isFirstLine) =>
return line === « » ? «
» :
isFirsLine ? « H1 … » :
;
This is a simple as I could get it while retaining readability
I'd have to see the rest of the code to decide whether or not this would be the best case but for now
Note that I've used
!=instead of!==in order to check for undefined. If you were going the strict approach you'd have used!==instead but because we're unaware of what will be coming inline. We're using a non-strict check here. I think this is a fairly simple solution in this case