FCC: DNA Pairing (JavaScript Intermediate Algorithm)

In FCC challenge DNA Pairing we’re generating pairing of DNA and then inserting it into a multidimensional array.

function pairElement(str) {
  return str;
}

pairElement("GCG");

We first need to split the str string into an array. Putting each letter in the array allows us to use the forEach function for each element of the array.

split = str.split('');

To split each letter in the string we need to delimit the separation by an empty string in the the split function. Once the str string has been split into the array, we do not need the str string and can repurpose it for returning our new generated DNA pairs. Before we can do that we need to clear the contents of str by assigning it as an array.

str = [];

The next step is to create a function that uses a switch statement to return the corresponding DNA pair sequence. The function takes an element from the split array.

function pair(element) {
  switch (element) {
    case 'A':
      return 'T';
    case 'T':
      return 'A';
    case 'C':
      return 'G';
    case 'G':
      return 'C';
    default:
      console.log('Error');
  }
}

The next algorithm executes after the str string has been split into the array. It uses the forEach function on each array element and passes the element to its inner function. The inner function passes each element to the pair function we created earlier stores the returned corresponding DNA pair into the basePair variable. Then the original DNA and the corresponding DNA pairing are pushed as an array into the str array which was changed from string previously.

split.forEach((element) => {
  basePair = pair(element);
  str.push([element, basePair]);
});

Finally the str array is returned to the calling function. The full code is below.

function pairElement(str) {
  let split = [];
  let basePair;

  split = str.split('');
  str = [];

  function pair(element) {
    switch (element) {
      case 'A':
        return 'T';
      case 'T':
        return 'A';
      case 'C':
        return 'G';
      case 'G':
        return 'C';
      default:
        console.log('Error');
    }
  }

  // split.forEach(function(element) {
  split.forEach((element) => {
    basePair = pair(element);
    str.push([element, basePair]);
  });

  console.log(str);
  return str;
}

pairElement('GCG');
pairElement('ATCGA');
pairElement('TTGAG');
pairElement('CTCTA');

Leave a Comment