javascriptregexrubystringstring-substitution

What is the JS equivalent to the Ruby :tr method?


In ruby I could do this:

def DNA_strand(dna)
  base_hash = { 'A' => 'T', 'T' => 'A', 'G' => 'C', 'C' => 'G' }
  dna.gsub(/[ATGC]/, base_hash)
end

I could also do this which would be exactly equivalent:

def DNA_strand(dna)
  Dna.tr(’ACTG’, ’TGAC’)
end

In JS is there any equivalent method to :tr in ruby?

Currently I can only think of solving this problem in JS like this:

function DNAStrand(dna){
  function matchBase(match, offset, string) {
    const base = { 'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G' };
    return `${base[match]}`;
  }
  return dna.replace(/[ATGC]/g, matchBase);
}

Any comments will be appreciated!


Solution

  • JavaScript has no built in .tr function, but you can add a prototype to the String object so that you can use a dna.tr('ACTG', 'TGAC'):

    String.prototype.tr = function(from, to) {
      let trMap = {};
      from.split('').forEach((f, i) => {
        trMap[f] = to[i] || to[to.length-1];
      });
      return this.replace(/./g, ch => trMap[ch] || ch);
    };
    
    const from = 'ACTG';
    const to   = 'TGAC';
    
    [
      'ATGC',
      'GCAT',
      'ATXY'
    ].forEach(dna => {
      console.log(dna + ' => ' + dna.tr(from, to));
    });
    Output:

    ATGC => TACG
    GCAT => CGTA
    ATXY => TAXY