1

I need to cycle through strings and replace them with complementary values. Here is what I have so far:

function DNAStrand(dna){
    const charMatrix = {
        A: "T",
        T: "A",
        C: "G",
        G: "C"
    }

    let i = 0;
    let length = dna.length;

    for (i; i < length; i++) {
        const currentChar = dna[i].toUpperCase();

        if (charMatrix[currentChar]) {
            dna[i] = charMatrix[currentChar];
        }
    }

    return dna;
}

The problem is that it enters the if, however it doesn't seem to change the value of the character.

Mike K
  • 7,621
  • 14
  • 60
  • 120

3 Answers3

3

Strings are immutable. This is one reason why strict mode is often preferable - the error will be explicit, rather than failing silently:

'use strict';
function DNAStrand(dna){
    const charMatrix = {
        A: "T",
        T: "A",
        C: "G",
        G: "C"
    }

    let i = 0;
    let length = dna.length;

    for (i; i < length; i++) {
        const currentChar = dna[i].toUpperCase();

        if (charMatrix[currentChar]) {
            dna[i] = charMatrix[currentChar];
        }
    }

    return dna;
}
DNAStrand('AGGCT');

Append to a new string instead, with +=:

'use strict';
function DNAStrand(dna){
    const charMatrix = {
        A: "T",
        T: "A",
        C: "G",
        G: "C"
    }

    let i = 0;
    let length = dna.length;
    let newStr = '';
    for (i; i < length; i++) {
        const currentChar = dna[i].toUpperCase();
        newStr += charMatrix[currentChar] || currentChar;
    }

    return newStr;
}
console.log(DNAStrand('AGGCT'));

Or use .replace with a callback function that looks up the property on the object:

'use strict';
function DNAStrand(dna){
    const charMatrix = {
        A: "T",
        T: "A",
        C: "G",
        G: "C"
    };
    return dna.replace(/[ATCG]/g, char => charMatrix[char]);
}
console.log(DNAStrand('AGGCT'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You could also take a different approach:

function DNAStrand(dna){
    const charMatrix = {
        A: "T",
        T: "A",
        C: "G",
        G: "C"
    };

    return dna.split("")
       .map(c => charMatrix[c])
       .join("");
}

console.log(DNAStrand("GATAGCACG"))

This splits the string into separate characters,
Maps the characters to their paired values,
Then joins the string back together again.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
0

You could iterate the characters and map new characters with Array.from.

function DNAStrand(dna){
    const charMatrix = { A: "T", T: "A", C: "G", G: "C" };
    return Array.from(dna, c => charMatrix[c.toUpperCase()] || c).join('');
}

console.log(DNAStrand('gataca'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392