Skip to content

Instantly share code, notes, and snippets.

@codecademydev
Created Aug 26, 2022
Embed
What would you like to do?
Codecademy export
// Returns a random DNA base
const returnRandBase = () => {
const dnaBases = ['A', 'T', 'C', 'G']
return dnaBases[Math.floor(Math.random() * 4)]
}
// Returns a random single strand of DNA containing 15 bases
const mockUpStrand = () => {
const newStrand = []
for (let i = 0; i < 15; i++) {
newStrand.push(returnRandBase())
}
return newStrand
}
// Factory Function for pAequor
const pAequorFactory = (number, array) => {
return {
specimenNum: number,
dna: array,
// Simulate Mutation
mutate() {
const randIndex = Math.floor(Math.random() * this.dna.length);
let newBase = returnRandBase();
while (this.dna[randIndex] === newBase) {
newBase = returnRandBase();
}
this.dna[randIndex] = newBase;
return this.dna;
},
// Compare DNA of different pAequor objects
compareDNA(otherObj) {
const similarities = this.dna.reduce((acc, curr, idx, arr) => {
if (arr[idx] === otherObj.dna[idx]) {
return acc + 1;
} else {
return acc;
}
}, 0);
const percentageOfDNAShared = (similarities / this.dna.length) * 100;
const percentageToDeci = percentageOfDNAShared.toFixed(2);
console.log(`${this.specimenNum} and ${otherObj.specimenNum} have ${percentageTo2Deci}% DNA in common.`);
},
// Chances of Survival
willLikelySurvive() {
let sum = 0;
for (let i = 0; i < this.dna.length; i++) {
if (this.dna[i] === "C" || this.dna[i] === "G") {
sum += 1;
};
}
let percentage = (sum / this.dna.length) * 100;
if (percentage >= 60) {
return true
} else {
return false
};
},
}
};
const survivingSpec = [];
let idCounter = 1;
while (survivingSpec.length < 30) {
let newOrg = pAequorFactory(idCounter, mockUpStrand());
if (newOrg.willLikelySurvive()) {
survivingSpec.push(newOrg);
}
idCounter++;
}
console.log(survivingSpec)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment