简体   繁体   English

使用多个三元运算符替换字符串的多个字符

[英]Replacing multiple characters of a string using multiple ternary operators

I am trying to solve a simple problem in JavaScript.我正在尝试解决 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例如,如果输入是ATCG ,则 output 将是UAGC

Initially I thought to convert the string to an array and then use map() on it.最初我想将字符串转换为数组,然后在其上使用map() 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.所以我寻找了其他方法,比如 RegExp,但似乎进行多次替换的唯一方法是链接多个replace() ,这确实会更加低效。

So I thought to use a for...of and I wrote this code:所以我想使用for...of并编写了以下代码:

 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 .似乎将C转换为G并将其他所有内容转换为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?任何人都知道实际发生了什么?

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.更好的方法是使用 object 来替换这些值。

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.只需使用简单的 object 查找即可。

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM