DEV Community

Discussion on: Critique my JS solution to this CodeWars Kata

Collapse
 
dmfay profile image
Dian Fay
const lookup = {
  'A': 'T',
  'T': 'A',
  'G': 'C',
  'C': 'G'
};

function DNAStrand(dna) {
  return [...dna].reduce((reversed, nucleotide) => {
    return reversed + lookup[nucleotide];
  }, '');
}

Defaulting to const declarations helps keep track of what's allowed to change. reduce is more appropriate when you need to accumulate results than the two-step of generating a new array and joining it. The hashtable lookup keeps the reducer body as short as possible, but there's nothing wrong with a switch per se.

Collapse
 
ztickm profile image
Salim MAHBOUBI

Clever!
Thanks Dian!

Collapse
 
dmerand profile image
Donald Merand • Edited

@dmfay This is a very elegant solution! I like that you're explaining the reasons why you did things like use a const etc.

One thing you didn't mention is the use of the spread syntax ([...dna]), which is definitely handy in JS when passing arrays around.

Collapse
 
moe64 profile image
Moe

wow I didn't know

[ ...dna] 

would automatically turn your string into an array. I always use

 dna.spilt("") 

I'm gonna change my solution to reflect this newfound knowledge.

Collapse
 
isaacdlyman profile image
Isaac Lyman

Came to the comments to post this exact solution. Very elegantly done.