Everyone Can Code!

JavaScript Kata #3: DNA to RNA Conversion


If you missed the introductory post, it's here. For a list of previously solved katas, please refer to the bottom of this page.

If this is your first time seeing my post, please note - these katas are probably randomly assigned per user so please don't go into Codewars thinking we will have exactly the same user experience, I am just posting these in the order that I got them.

Kata #3

DESCRIPTION:

Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T').

Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structure and contains no Thymine. In RNA Thymine is replaced by another nucleic acid Uracil ('U').

Create a function which translates a given DNA string into RNA.

For example:

"GCAT" => "GCAU"
The input string can be of arbitrary length - in particular, it may be empty. All input is guaranteed to be valid, i.e. each input string will only ever consist of 'G', 'C', 'A' and/or 'T'.

Starting code:

function DNAtoRNA(dna) {
  // create a function which returns an RNA sequence from the given DNA sequence
}

My attempt:

function DNAtoRNA(dna) {
  // create a function which returns an RNA sequence from the given DNA sequence
  let arrayedRNA = ""
  for (let i = 0 ; i < dna.length ; i++){
    if(dna[i] == "T"){
      arrayedRNA += "U"
    } else{
      arrayedRNA += dna[i]
    }
  }
  return arrayedRNA
}

Worked!

Now on to the 'Best Practices':

function DNAtoRNA(dna){
  return dna.replace(/T/g, 'U');
}

Learned something new today. Didn't know there was a .replace method which could be used for strings. What I knew going into the problem though was that string variables are arrays by themselves and I could iterate among each character as an individual element in the string which is why I approached the problem like that. Upon scrolling down, I saw that my approach is ranked #5. No hard feelings, my logic is still sound. Just can't beat that single line of code to solve the whole challenge but now we know, don't we? Also learned that there is a .split and a .join method which ranked #3 in 'Best Practice':

function DNAtoRNA(dna) {
  return dna.split("T").join("U");
}

That's it for Kata #3, stay tuned for more katas to be solved!

Link to Kata #1: Square(n) Sum

Link to Kata #2: Convert a Number to a String

How do you rate this article?

6


YayoDrayber
YayoDrayber

A Yayo, A Drayber, among others.


Learn To Code With Me
Learn To Code With Me

Just started with Codewars and will be posting the solutions I came up with here and the apparent best practices.

Publish0x

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.