Skip to content

Instantly share code, notes, and snippets.

@shubhsaur
Created April 29, 2022 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shubhsaur/b1207230d856832fd33d8e8e28586df5 to your computer and use it in GitHub Desktop.
Save shubhsaur/b1207230d856832fd33d8e8e28586df5 to your computer and use it in GitHub Desktop.
Javascript Project - Mysterious Organism
// 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
}
//Organism object factory function
const pAequorFactory = (specimenNum, dna) => {
return {
specimenNum: specimenNum,
dna: dna,
//mutate fn for randomly selecting a base in the object’s dna property and changing the current base to a different base.
mutate() {
console.log(dna);
const index = Math.floor(Math.random() * 15);
console.log(index);
const currentBase = dna[index];
const randomBase = returnRandBase();
console.log(randomBase);
if(currentBase !== randomBase){
dna[index] = randomBase;
}
return dna;
},
//compare the current pAequor‘s .dna with the passed in pAequor‘s .dna and compute how many bases are identical and in the same locations.
compareDNA(otherObj){
let count = 0;
for(let i = 0; i < this.dna.length; i++){
const otherOrg = otherObj.dna[i];
const currentOrg = this.dna[i];
if(currentOrg === otherOrg){
count++;
}
}
const percDNA = Math.round((count / this.dna.length) * 100);
return `specimen #1 and specimen #2 have ${percDNA}% DNA in common`;
},
//.willLikelySurvive() returns true if the object’s .dna array contains at least 60% 'C' or 'G' bases. Otherwise, .willLikelySurvive() returns false.
willLikelySurvive(){
let count = 0;
for(let i = 0; i < this.dna.length; i++){
const base = this.dna[i];
if(base === 'C' || base === 'G'){
count++;
}
}
const percDNA = Math.round((count / this.dna.length) * 100);
if(percDNA >= 60){
return true;
}else{
return false;
}
}
}
}
// console.log(pAequorFactory(1, mockUpStrand()));
// const obj = pAequorFactory(1, mockUpStrand());
// console.log(obj.mutate());
// const obj1 = pAequorFactory(1, mockUpStrand());
// const obj2 = pAequorFactory(2, mockUpStrand());
// console.log(obj1.compareDNA(obj2));
// console.log(obj1.willLikelySurvive());
const survivedOrg = [];
let i = 1;
while(survivedOrg.length !== 30){
let obj = pAequorFactory(i, mockUpStrand());
if(obj.willLikelySurvive()){
survivedOrg.push(obj);
}
i++;
}
console.log(survivedOrg);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment