calculateAge.js (8kyu 39)

Codewars 알고리즘 풀이


Description

  • Your task is to write a function that takes two parameters: the year of birth and the year to count years in relation to.
    • 출생년도부터 해당년도까지 계산하는 함수를 작성한다.



Solution 01

function calculateAge(birthYear, currentYear) {
  const age = currentYear - birthYear;
  
  if (age === 1) return 'You are 1 year old.';
  else if (age === -1) return 'You will be born in 1 year.';
  else if (age > 0) return `You are ${age} years old.`;
  else if (age < 0) return `You will be born in ${-age} years.`;
  else return 'You were born this very year!';
}

calculateAge(1988, 1988);  // You were born this very year!
calculateAge(1988, 1989);  // You are 1 year old.
calculateAge(1988, 2020);  // You are 32 years old.
calculateAge(1988, 1987);  // You will be born in 1 year.
calculateAge(2040, 2020);  // You will be born in 20 years.


Solution 02

function calculateAge(birthYear, currentYear) {
  let year = Math.abs(birthYear - currentYear) === 1 ? 'year' : 'years';
  
  if (birthYear === currentYear) return 'You were born this very year!';
  if (birthYear < currentYear) return `You are ${currentYear - birthYear} ${year} old.`;
  if (birthYear > currentYear) return `You will be born in ${-currentYear + birthYear} ${year}.`;
}

calculateAge(1988, 1988);  // You were born this very year!
calculateAge(1988, 1989);  // You are 1 year old.
calculateAge(1988, 2020);  // You are 32 years old.
calculateAge(1988, 1987);  // You will be born in 1 year.
calculateAge(2040, 2020);  // You will be born in 20 years.