How can I improve and shorten this block of code?

CocoFlade :

This function takes a string of DNA such as 'GTCA' and returns an array containing correctly matched DNA pairs.

function pairDNA(dna) {

  const pairs = []

  for (let i = 0; i < dna.length; i ++) {

    if (dna[i] === "C" | dna[i] === "c") {
      pairs.push("CG");
    } else if (dna[i] === "G"| dna[i] === "g") {
      pairs.push("GC");
    } else if (dna[i] === "T"| dna[i] === "t") {
    pairs.push("TA");
    } else if (dna[i] === "A"| dna[i] === "a") {
      pairs.push("AT");
    }
  }

return pairs;
}

This is correct. However i'm trying to find a shorter, simpler way of writing it. Can anyone help me with what I should be using?

Maheer Ali :

You can improve you code in following steps:

  • When there are multiple if statements and all have same structure you probably need to use an object
  • You need to check of both uppercase and lowercase. Just use toLowerCase() on input.
  • You can split the string and map() it rather than creating an array push() values into it.

function pairDNA(dna) {
  const obj = {
    c: 'CG',
    g: 'GC',
    t: 'TA',
    a: "AT"
  }
  return dna.split('').map(x => obj[x.toLowerCase()])

}

If the string could contain anything other the specific letters then you need to filter() the undefined values after map

return dna.split('').map(x => obj[x.toLowerCase()]).filter(x => x !== undefined)

Another better is mentioned by @RobG in the comments that we can remove the unwanted letters from string before looping through it.

return dna
        .toLowerCase()
        .replace(/[^cgta]/g,'')
        .split('')
        .map(x => obj[x])

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=6900&siteId=1