Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate age on Class when creating an instance

I would like to automatically calculate and set an age when creating an instance.
I made a function that calculates and returns an age.
It works, but I wonder if it’s possible to write the function/method in the Member Class without using the global space.

class Member {
  static id = 0;

  constructor(firstName, lastName, birthDay) {
    Member.id++;
    this.id = Member.id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthDay = birthDay;
    this.age = getAge(birthDay);
  }
}

const m1 = new Member('Oliver', 'Cruz', '11/13/1990');
console.log('m1:', m1.age); // 32 (as of Nov 13rd, 2022)

const m2 = new Member('Sophia', 'Brown', '11/30/1992');
console.log('m2:', m2.age); // 29 (as of Nov 13rd, 2022)

/**
 * Calculate age function
 * @param {String} birthDay - ex '11/13/1990'
 * @returns {Number} - age
 */
function getAge(birthDay) {
  const now = new Date();
  const bd = new Date(birthDay);
  const diff = now - bd;
  const age = new Date(diff).getFullYear() - 1970;

  return age;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can add it as a static method on the Member class.

class Member {
  static id = 0;

  constructor(firstName, lastName, birthDay) {
    Member.id++;
    this.id = Member.id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.birthDay = birthDay;
    this.age = Member.getAge(birthDay);
  }

  /**
   * Calculate age function
   * @param {String} birthDay - ex '11/13/1990'
   * @returns {Number} - age
   */
  static getAge = (birthDay) => {
    const now = new Date();
    const bd = new Date(birthDay);
    const diff = now - bd;
    const age = new Date(diff).getFullYear() - 1970;

    return age;
  }
}

const m1 = new Member('Oliver', 'Cruz', '11/13/1990');
console.log('m1:', m1.age); // 32 (as of Nov 13rd, 2022)

const m2 = new Member('Sophia', 'Brown', '11/30/1992');
console.log('m2:', m2.age); // 29 (as of Nov 13rd, 2022)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading