Friday, March 16, 2018

Key Value Pair Statements - Better for the eyes, but better performance?

There have been two challenges on Free Code Camp now that I went down the road of using if statements. It started getting ugly with all those if and else if statements. You could use a case statement for each of the if statements, the case statement could possibly be easier to read and possibly have a faster performance.

Below is an example for possible DNA strings:

function pairElement(str) {
var myArray = str.split('');
var returnArray = [];
for (st in str) {
if(myArray[st] == 'G') {
returnArray.push([myArray[st], 'C']);
}
else if(myArray[st] == 'C') {
returnArray.push([myArray[st], 'G']);
}
else if(myArray[st] == 'A') {
returnArray.push([myArray[st], 'T']);
}
else {
returnArray.push([myArray[st], 'A']);
}
}

But then I got thinking, what if there were a dictionary or map that would allow someone to look up the index and see what the value output is for the item. I believe I had seen something like that before so I started searching. Turns out a map is exactly what I needed.

This technique allows me to create a map, or a key value pair, that will let me look up the value I am looking up and see it's matching string. Your first key value set G: 'C' will look up anytime your key is G it will output C.

By splitting the input string by their characters, one you are then able to use that item as the lookup for your key and return the value you need.

function pairElement(str) {
  var pairMap = {G:'C', C:'G', A:'T', T:'A'};
  var myArray = str.split('');
  
  for(var st in str) {
    myArray[st] = [myArray[st], pairMap[myArray[st]]];
  }
  
  
  return myArray;
}

The code is much easier to read and I am guessing it will have better performance as it doesn't have to check each if/else if statements.

"Nothing is work unless you'd rather be doing something else." - George Halas

No comments: