skip to Main Content

In the pAequorFactory(), when invoking that function to create an object. I want the .specimenNum to be unique for all objects. Check the code below

const pAequorFactory = (specimenNum, dna) => {
  return {
    specimenNum,
    dna,

    mutate() {
      randomBaseIndex = Math.floor[Math.random * 15];
      mutatedBase = returnRandBase();
      if (this.dna[randomBaseIndex] !== mutatedBase) {
        this.dna[randomBaseIndex] === mutatedBase;
        return this.dna;
      } else {
        mutate();
      }
    },

    compareDNA(object) {
      for (i = 0; i < 15; i++) {
        let j = 0;
        if (object.dna[i] === this.dna[i]) {
          j++;
        }
        let commonPercentage = (j / 15) * 100;
      }
      return `specimen #${this.specimenNum} and specimen #${object.specimenNum} have ${commonPercentage}% DNA in common`;
    },

    willLikelySurvive() {
      for (i = 0; i < 15; i++) {
        let j = 0;
        if (this.dna[i] === "C" || this.dna[i] === "G") {
          j++;
        }
        let survivePercentage = (j / 15) * 100;
      }
      return survivePercentage >= 60;
    },
  };
};

I haven’t tried anything yet but I am thinking of a way to compare .specimenNum of each object.

2

Answers


  1. The best way is to use closure

    const pAequorFactory = () => {
      let specimenCount = 0; // To keep track of the number of specimens created
    
      return (dna) => {
        specimenCount++; // Increment the specimen count for each new specimen
        return {
          specimenNum: specimenCount, // Assign a unique specimen number
          dna,
    
          // Your remaining object properties here
        };
      };
    };
    
    // Example usage:
    const createSpecimen = pAequorFactory();
    const specimen1 = createSpecimen('ATCGATCGATCGATC');
    const specimen2 = createSpecimen('GCTAGCTAGCTAGCT');
    
    console.log(specimen1.specimenNum); // Output: 1
    console.log(specimen2.specimenNum); // Output: 2
    
    

    This will create unique object each time you call createSpecimen, unique property will be specimenNum.

    Login or Signup to reply.
  2. You can create a global numeric value and increment it:

    let specimenNumCount = 0;
    const pAequorFactory = dna => {
      return {
        specimenNum: ++specimenNumCount,
        dna,
    
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search