The Kata
The exercice basically asks to convert any 'T' to 'A' any 'C' to 'G' and vice versa for any given string.
My solution
I know it might not be the exemplary solution but it was the first thing that popped in my head.
I wrote it first like this:
function DNAStrand(dna){
let map = Array.prototype.map;
let reversedDna = map.call(dna, function(x) {
let y;
switch(x){
case 'A': y = 'T'; break;
case 'T': y = 'A'; break;
case 'G': y = 'C'; break;
case 'C': y = 'G'; break;
}
return y;
});
return reversedDna.join('');
}
then I thought to myself: "I can remove that y variable." So I did:
function DNAStrand(dna){
let map = Array.prototype.map;
let reversedDna = map.call(dna, function(x) {
let y;
switch(x){
case 'A': return 'T'; break;
case 'T': return 'A'; break;
case 'G': return 'C'; break;
case 'C': return 'G'; break;
}
});
return reversedDna.join('');
}
Then I thought: "I can get rid of the break lines since the return statements are already breaking, can't I?"
function DNAStrand(dna){
let map = Array.prototype.map;
let reversedDna = map.call(dna, function(x) {
let y;
switch(x){
case 'A': return 'T';
case 'T': return 'A';
case 'G': return 'C';
case 'C': return 'G';
}
});
return reversedDna.join('');
}
Is there any way to improve my solution? Do you have another way of doing that? Leave your remarks in the comments
Top comments (9)
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 andjoin
ing it. The hashtable lookup keeps the reducer body as short as possible, but there's nothing wrong with aswitch
per se.@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.wow I didn't know
would automatically turn your string into an array. I always use
I'm gonna change my solution to reflect this newfound knowledge.
Came to the comments to post this exact solution. Very elegantly done.
Clever!
Thanks Dian!
Thanks Sean ! I don't know why I didn't think of reduce...
I see no problem with your solution. I like how you iteratively improved your solution.
Here is my solution.
or in one line
Nice and clean. Thanks Maurice!