How to returns correctly matched array?

女生的网名这么多〃 提交于 2019-12-13 02:15:07

问题


I have a function that takes a string of DNA and how to return correctly matched dna array The code that I have tried:

function checkDNA(dna) {
   var dnaarr = [];


    for(var i = 0; i < dna.length; i++) {
         var str = [];
str.push(dna[i]); //pushing current str[i]
      if(dna[i].indexOf('') === 0) {
        var a = str.push('sd');
      }
      if(dna[i].indexOf('GGC') === 0) {
        var b = str.push("GC", "GC", "CG");
      }
      if(dna[i].indexOf('gat') === 0) {
        var c = str.push("GC", "AT", "TA");
      }
      if(dna[i].indexOf('PGYYYHVB') === 0) {
        var d = str.push('GC');
      }
dnaarr.push(str); //pushing the array dna to the main array dnaarr
    }


    return dnaarr;
}

回答1:


You could take an object for the nucleobases and take the characters of the string for getting the values for each character.

For unknow characters, a later filtering is applied.

function pair(string) {
    var nucleobases = { G: 'C', C: 'G', T: 'A', A: 'T' };

    return Array
        .from(string.toUpperCase(), s => s in nucleobases && s + nucleobases[s])
        .filter(Boolean);
}

console.log(pair('GTTC'));



回答2:


You are thinking this in the wrong way. You have to register those values.

Think about in the db way.

Here is an exmaple.

var dnaRules = {}    
/// register DNA
register = function(key) {
var item = {};
       if (dnaRules[key])
           return dnaRules[key];
         else {
          item[key]= [];
          item.equal = function(value){
          item["data"] = value;
          }
          dnaRules[key]= item;
          }
          return item;
} 
register("GGC").equal(['GC', 'GC', 'CG']);
register("gat").equal(["GC", "AT", "TA"]);
register("PGYYYHVB").equal(["GC", "GC", "GC"]);
// Search DNA
search = function(value){
  var key = null;
  Object.keys(dnaRules).forEach(function(v){
 if (v.toLowerCase().indexOf(value.toLowerCase())>=0)
  key = v;
  });
  
  return key== null ? null : dnaRules[key]
}

var item = search("ggc"); // if the item dose not exist you get null
// now display the items 
console.log(item.data)
/// or you could change them even 
// item.equal([])


来源:https://stackoverflow.com/questions/56409738/how-to-returns-correctly-matched-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!