Replacing multiple characters of a string using multiple ternary operators

Viewed 63

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?

2 Answers

If you really like to take ternaries, you could take this approach with multiple conditions.

r += x === 'G'
    ? 'C'
    : x === 'C'
        ? 'G'
        : x === 'T'
            ? 'A'
            : 'U'

A better approach is to take an object for replacing the values.

nucleobases = { G: 'C', C: 'G', T: 'A', A: 'U' }

Later take replacements with

r += nucleobases[x];

This can be done with a ternary, but does not make much sense, but it can be done. You need to do the check for each letter.

let s = 'ATGC*';

let r = '';

for (const x of s) r += 
  x === "G" ? "C" : 
    x === "C" ? "G" : 
     x === "T" ? "A" :
       x === "A" ? "U" : x;

console.log(r);

Ternary is way too complicated for this. Just use a simple object look up.

var replacements = {
  G: 'C',
  C: 'G',
  T: 'A',
  A: 'U',
}

let s = 'ATGC*';

let r = '';

for (const x of s) r += replacements[x] || x;

console.log(r);

And how I would code it

const replacements = {
  G: 'C',
  C: 'G',
  T: 'A',
  A: 'U',
}

const s = 'ATGC*';

const re = new RegExp(`[${Object.keys(replacements).join('')}]`,'g');

const r = s.replace(re, x => replacements[x]);
console.log(r);

Related