Algorithm Scripting – DNA Pairing

Now that I am coding semi-daily again, completing the scripting challenges on FreeCodeCamp is much less intimidating. One in particular that was bothering me for a minute was the DNA Pairing challenge.

I can’t quite remember why this one stumped me previously – I didn’t find it that difficult to complete. My original solution used a for loop and 4 if-statements to create the array of paired elements.

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

I wanted to use a switch initially, but kept getting stuck in execution. After getting it working the first time, I felt more confident in getting it to work again with slightly different code.

I noticed that only one element would get pushed to the array of pairs. Why? The break keyword stops the switch block.

The break meant that after one condition checked as true, the switch block would break and stop running. If I removed the break, everything that came after it in the switch block would run.

After some Googling and sighs of frustration, I learned that if I moved the switch block to its own function, I could call the function on each character instead.

function pairElement(str) {
  var pairs =[];
  
  for(var i=0; i < str.length; i++) {
    pairOff(str[i]);
  }
  
  function pairOff(char) {
    switch(char) {
      case "A" : 
        pairs.push(["A", "T"]);
        break;
      case "T": 
        pairs.push(["T", "A"]);
        break;
      case "C": 
        pairs.push(["C", "G"]);
        break;
      case "G": 
        pairs.push(["G", "C"]);
        break;        
    }
  }
  
return pairs;
    
}



And, voila! I successfully refactored my code.

Now, I only have 2 more challenges in the Intermediate Scripting Challenges section and 4 more Front-End Projects to complete before I am eligible to claim my Front End Development Certificate.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s