Mysterious Organism Challenge Project (JavaScript)

Okay, I caught that I had a typo which is why my call wasn’t working. I’m using the code shown below and it works correctly.

// Returns a random DNA base
const returnRandBase = () => {
	const dnaBases = ['A', 'T', 'C', 'G'];
	return dnaBases[Math.floor(Math.random() * 4)];
};

// Returns a random single stand of DNA containing 15 bases
const mockUpStrand = () => {
	const newStrand = [];
	for (let i = 0; i < 15; i++) {
		newStrand.push(returnRandBase());
	}
	return newStrand;
};

// Below is what I had to write for the assignment
const pAequorFactory = (specimanNum, dna) => {
	return {
		specimanNum,
		dna,
		mutate() {
			// create a variable randIndex that's equal to a random number less than or equal to the length of the dna array. This will be used to randomly select a base from the dna array/sequence
			const randIndex = Math.floor(Math.random() * this.dna.length);
			// create a new random base
			let newBase = returnRandBase();

			// while the base at the dna array index of whatever number is returned by randIndex is equal to or the same as the newBase that we are trying to generate : generate a newBase. This will continue until we get a different base.
			while (this.dna[randIndex] === newBase) {
				newBase = returnRandBase();
			}
			// using the new and different base generated by the above while loop, update/change/mutate the base found at randIndex of the dna sequence
			this.dna[randIndex] = newBase;
			// return the mutated dna sequence/array
			return this.dna;
		},
		compareDNA(otherOrg) {
			// compare the current dna sequence with the passed in dna sequence "otherOrg" to see how many bases are identical and at the same location.
			// use Array.prototype.reduce to create a new array of all bases that are identical and in the same location for both sequences. syntax = reduce((previousValue, currentValue, currentIndex, array) => { ... }, initialValue)
			const similarities = this.dna.reduce((acc, curr, idx, arr) => {
				if (arr[idx] === otherOrg.dna[idx]) {
					return acc + 1;
				} else {
					return acc;
				}
			}, 0);
			const percentOfDNAshared = (similarities / this.dna.length) * 100;
			const percentageTo2Deci = percentOfDNAshared.toFixed(2);
			// print a message that states the percentage of DNA the two have in common

			console.log(`${this.specimanNum} and ${otherOrg.specimanNum} have ${percentageTo2Deci}% DNA in common.`);
		},
	};
};

// create an instance of pAequorFactory so that the function is only called once so that we can then mutate that instance and compare the dna sequences.
const pAequor1 = pAequorFactory(1, mockUpStrand());
const pAequor2 = pAequorFactory(2, mockUpStrand());
// save the mutated dna sequence to its own instance
// const mutated1 = pAequor1.mutate();
// const mutated2 = pAequor2.mutate();
// log the original sequence
console.log(pAequor1.dna);
console.log(pAequor2.dna);
// log the mutated dna sequence
// console.log(mutated1);
// console.log(mutated2);
// log the compareDNA output
pAequor1.compareDNA(pAequor2);

I further improved the solution code for step #5 .compareDNA() to include more notes explaining what’s going on as well as detailed logging of what’s happening when we use the .reduce() method as it iterates through the arrays. I hope this helps anyone else who is struggling as I was.

Sample output:
PS C:\Code\mystery-organism-starter> node main.js
NOT A MATCH!
total = 0
current = C
Index = 0

NOT A MATCH!
total = 0
current = A
Index = 1

MATCH!
total = 0
current = G
Index = 2

NOT A MATCH!
total = 1
current = C
Index = 3

MATCH!
total = 1
current = T
Index = 4

MATCH!
total = 2
current = T
Index = 5

MATCH!
total = 3
current = C
Index = 6

NOT A MATCH!
total = 4
current = G
Index = 7

NOT A MATCH!
total = 4
current = C
Index = 8

NOT A MATCH!
total = 4
current = T
Index = 9

NOT A MATCH!
total = 4
current = G
Index = 10

MATCH!
total = 4
current = A
Index = 11

NOT A MATCH!
total = 5
current = A
Index = 12

NOT A MATCH!
total = 5
current = T
Index = 13

NOT A MATCH!
total = 5
current = C
Index = 14

Similarities Total = 5
Original Array = C,A,G,C,T,T,C,G,C,T,G,A,A,T,C
Other Array = T,T,G,G,T,T,C,C,T,A,C,A,G,C,G
Specimen 1 and 2 have 33.33% DNA in common.

// Returns a random DNA base
const returnRandBase = () => {
	const dnaBases = ['A', 'T', 'C', 'G'];
	return dnaBases[Math.floor(Math.random() * 4)];
};

// Returns a random single stand of DNA containing 15 bases
const mockUpStrand = () => {
	const newStrand = [];
	for (let i = 0; i < 15; i++) {
		newStrand.push(returnRandBase());
	}
	return newStrand;
};

// Below is what I had to write for the assignment
const pAequorFactory = (specimenNum, dna) => {
	return {
		specimenNum,
		dna,
		mutate() {
			// create a variable randIndex that's equal to a random number less than or equal to the length of the dna array. This will be used to randomly select a base from the dna array/sequence
			const randIndex = Math.floor(Math.random() * this.dna.length);
			// create a new random base
			let newBase = returnRandBase();

			// while the base at the dna array index of whatever number is returned by randIndex is equal to or the same as the newBase that we are trying to generate : generate a newBase. This will continue until we get a different base.
			while (this.dna[randIndex] === newBase) {
				newBase = returnRandBase();
			}
			// using the new and different base generated by the above while loop, update/change/mutate the base found at randIndex of the dna sequence
			this.dna[randIndex] = newBase;
			// return the mutated dna sequence/array
			return this.dna;
		},
		compareDNA(otherOrg) {
			// compare the current dna sequence with the passed in dna sequence "otherOrg" to see how many bases are identical and at the same location.
			// use Array.prototype.reduce to create a new array of all bases that are identical and in the same location for both sequences. syntax = reduce((previousValue, currentValue, currentIndex, array) => { ... }, initialValue)
			const similarities = this.dna.reduce((total, curr, idx, arr) => {
				// if the array we call this method on (pAequor1 as shown below) has the same base value at each index location as the array that we pass into the method (pAequor2 as shown below) then return total +1 else return just the total.
				// To help illustrate what's going on with the reduce method, we can log the elements of the callback function as it iterates through the arrays. Note: we do not need to log the "arr" element because it is the array that we are calling this method on which we log below between the total similarities and the DNA% in common message
				if (arr[idx] === otherOrg.dna[idx]) {
					console.log('MATCH!');
					console.log(`	total = ` + total);
					console.log(`	current = ` + curr);
					console.log(`	Index = ` + idx + '\n');
					return total + 1;
				} else {
					console.log('NOT A MATCH!');
					console.log(`	total = ` + total);
					console.log(`	current = ` + curr);
					console.log(`	Index = ` + idx + '\n');
					return total;
				}
				// initialize the total value as '0'
			}, 0);
			// divide the number of similarities returned by the .reduce() method by the length of the array and multiply it by 100 to get the percentage of shared DNA and save that value to a variable percentOfDNAshared
			const percentOfDNAshared = (similarities / this.dna.length) * 100;
			// set the length of the percentOfDNAshared to two decimal places example: 100.00%
			const percentageTo2Deci = percentOfDNAshared.toFixed(2);
			// print the total number of similarities between the two arrays
			console.log(`Similarities Total = ` + similarities);

			// Log the two arrays being compared
			// this.dna = the array we append with compareDNA()
			console.log(`Original Array = ` + this.dna);
			// otherOrg.dna = the array we pass into compareDNA(this_one)
			console.log(`Other Array    = ` + otherOrg.dna);

			// print a message that states the percentage of DNA the two have in common
			console.log(`Specimen ${this.specimenNum} and ${otherOrg.specimenNum} have ${percentageTo2Deci}% DNA in common.\n`);
		},
	};
};

// create instances of pAequorFactory so that the function is only called once so that we can then mutate that instance and compare the dna sequences.
const pAequor1 = pAequorFactory(1, mockUpStrand());
const pAequor2 = pAequorFactory(2, mockUpStrand());

// save the mutated dna sequences to their own instances
// const mutated1 = pAequor1.mutate();
// const mutated2 = pAequor2.mutate();

// log the original sequence
// console.log(pAequor1.dna);
// console.log(pAequor2.dna);

// log the mutated dna sequence
// console.log(mutated1);
// console.log(mutated2);

// call the compareDNA method to compare the pAequor2 dna sequence to the original pAequor dna sequence.
pAequor1.compareDNA(pAequor2);

1 Like
// Returns a random DNA base
const returnRandBase = () => {
    const dnaBases = ['A', 'T', 'C', 'G'];
    return dnaBases[Math.floor(Math.random() * 4)];
};

// Returns a random single stand of DNA containing 15 bases
const mockUpStrand = () => {
    const newStrand = [];
    for (let i = 0; i < 15; i++) {
        newStrand.push(returnRandBase());
    }
    return newStrand;
};

const pAequorFactory = (specimenNum, dna) => {
    return {
        specimenNum,
        dna,
        mutate() {
            const dnaBase = ['A', 'T', 'C', 'G']
            const randIndex = Math.floor(Math.random() * this.dna.length)
            const dnaSelected = this.dna[randIndex]
            dnaBase.splice(dnaBase.findIndex((element) => element === dnaSelected), 1)
            this.dna[randIndex] = dnaBase[Math.floor(Math.random() * 3)]
            return this.dna
        },
        compareDNA(pAequor) {
            let counter = 0;
            for (let i = 0; i < this.dna.length; i++) {
                if (this.dna[i] === pAequor.dna[i]) {
                    counter++;
                }
            }
            console.log(`${this.specimenNum} and ${pAequor.specimenNum} have ${Math.floor(counter / this.dna.length * 100)}% DNA in common.`)
        },
        willLikelySurvive() {
            let counter = 0;
            this.dna.forEach(i => {
                if (i === 'C' || i === 'G') {
                    counter += 1
                }
            })
            console.log(counter)
            return counter / this.dna.length >= 0.6
        }
    }
}


console.log(pAequorFactory(1, mockUpStrand()).willLikelySurvive())