I am trying to solve a simple problem in JavaScript. I have to take a string of characters and do the following substitutions:
G -> C
C -> G
T -> A
A -> U
So for example if the input is ATCG the output would be UAGC
Initially I thought to convert the string to an array and then use map() on it. But why to iterate over the string twice when the job could be done in a single iteration?
So I looked for other ways, like RegExp, but it seems that the only way to do multiple substitutions is to chaining multiple replace() and this would indeed be even more inefficient.
So I thought to use a for...of and I wrote this code:
let s = 'ATGC*';
let r = '';
for(const x of s) r += x === 'C' ? 'G' : 'G' ? 'C' : 'T' ? 'A' : 'A' ? 'U' : '-NaN-';
console.log(r);
It seems to convert C to G and everything else to C.
I think it should work like this:
x === // if the current character is equal to
'C' ? // `C`
'G' : // r += `G`
'G' ? // else if it is equal to `G`
'C' : // r += `C`
'T' ? // else if it is equal to `T`
'A' : // r += `A`
'A' ? // else if it is equal to `A`
'U' : // r += `U`
'-NaN-'; // else it is not a nucleotide
Anyone with an idea of what is actually going on?