JavaScript DNAStrand(A-T,C-G)

Description:

Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.

In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have function with one side of the DNA (string, except for Haskell); you need to get the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).

Examples

DNAStrand ("ATTGC") // return "TAACG"
DNAStrand ("GTAT") // return "CATA"

方法一:使用正则配对

function DNAStrand(dna){
  return dna.replace(/A/g, 't').replace(/T/g, 'a').replace(/C/g, 'g').replace(/G/g, 'c').toUpperCase();
}

console.log(DNAStrand("ATTGC"));//TAACG
console.log(DNAStrand("GTAT"));//CATA

方法二:使用 < key,value >键值对

var pairs = {'A':'T','T':'A','C':'G','G':'C'};
function DNAStrand(dna) {
  return dna.replace(/./g, function(y) {
    return pairs[y];
  });
}

console.log(DNAStrand("ATTGC"));//TAACG
console.log(DNAStrand("GTAT"));//CATA

方法三

  • split() 方法用于把一个字符串分割成字符串数组( 如:"2:3:4:5".split("😊 //将返回["2", "3", "4", "5"])
  • map() 方法返回一个新数组,数组中的元素为原始数组元素按顺序依次调用函数处理后的值
array.map(function(currentValue,index,arr), thisValue)

currentValue(必须)当前元素的值
index (可选)     当前元素的索引值
arr (可选)       当前元素属于的数组对象
thisValue(可选)  对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
                  如果省略了 thisValue ,"this" 的值为 "undefined"
var pairs = {'A':'T','T':'A','C':'G','G':'C'};
function DNAStrand(dna){
  return dna.split('').map(function(y){ return pairs[y] }).join('');
}

console.log(DNAStrand("ATTGC"));//TAACG
console.log(DNAStrand("GTAT"));//CATA
posted @ 2017-08-28 15:18  芒果夏夏  阅读(724)  评论(1编辑  收藏  举报