Be Brav3

FCC: DNA Pairing (JavaScript Intermediate Algorithm)

September 21, 2016

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

[js]

function pairElement(str) {

return str;

}

pairElement(“GCG”);

[/js]

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.

[js]

split = str.split(”);

[/js]

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.

[js]

str = [];

[/js]

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.

[js]

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’);

}

}

[/js]

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.

[js]

split.forEach((element) => {

basePair = pair(element);

str.push([element, basePair]);

});

[/js]

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

[js]

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’);

[/js]