Could anyone explain how this code works? Particularly the callback function, I am confused as to why it loops through the entire input rather just part of the input
function DNAStrand(dna){
return dna.replace(/[ACGT]/g, function(l){ return pairs[l] });
}
var pairs = {
A:'T',
T:'A',
G:'C',
C:'G'
};
Also, This was my solution for the same task(on code wars) my code compiled in 4 ms which I thought was pretty good!
function DNAStrand(dna){
//your code here
var dnaArray = dna.slice("");
var compliment = []; //push all values here
for(i=0; i<dnaArray.length; i++){ //loops through whole array
if(dnaArray[i] === 'T'){compliment.push('A')}
if(dnaArray[i] === 'A'){compliment.push('T')}
if(dnaArray[i] === 'G'){compliment.push('C')}
if(dnaArray[i] === 'C'){compliment.push('G')}
}
var result = compliment.join("");
return result;
}
Besides for being less elegant then the first solution, is there anything wrong with this solution versus the other if they both produce the same outcome? Just trying to understand general rules about best practices!
/[ACGT]/g
performs a global (from the /g
flag) search for A
, C
, G
, or T
within the dna
string A
, C
, G
, or T
), it does a replacement using the callback function A
, C
, G
, or T
) in pairs
and return the corresponding value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.