Intermediate Algorithm Scripting - DNA Pairing

Hey everyone! I would like some of you more experienced programmers to critique my solution to this problem. After my code passed all the tests, I compared it to the solutions on the “Get a Hint” page and realized it was quite different. I was wondering if there is a reason that the solutions given used the switch method instead of what I did. I’m still a newbie so I’m trying to learn best practices, how to write clean code, etc. Thanks :slight_smile:

Your code so far

function pairElement(str) {
  let newArr = [];
  for (let i = 0; i < str.length; i++) {
    if (str[i] === "G") {
      newArr.push(["G", "C"]);
    } else if (str[i] === "C") {
      newArr.push(["C", "G"]);
    } else if (str[i] === "T") {
      newArr.push(["T", "A"]);
    } else {
      newArr.push(["A", "T"]);
    }
  }
  return newArr;
}

console.log(pairElement("GCG"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36

Challenge Information:

Intermediate Algorithm Scripting - DNA Pairing

Because some people think that a switch looks cleaner than a bunch of else/ifs. But then there are some people that would never use a switch and wish it was removed from the language.

For this simple algorithm, your solution is just fine. Unless they find new letters in DNA then you won’t have the need to change this code. On the other hand, if you knew that you were going to be adding more cases down the road, then you might want to consider solution 2 in the help as that would probably be the easiest and cleanest way to add them.

Gotcha. Thank you! I appreciate the explanation, that makes more sense now.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.