calculateAge.js (8kyu 95)

Codewars 알고리즘 풀이


Problem

  • 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) {
  let 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, 2019);  // You are 31 years old.
calculateAge(1988, 1987);  // You will be born in 1 year.
calculateAge(2030, 2019);  // You will be born in 11 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, 2019);  // You are 31 years old.
calculateAge(1988, 1987);  // You will be born in 1 year.
calculateAge(2030, 2019);  // You will be born in 11 years.

Math.abs() 메소드

주어진 숫자의 절대값(absolute value)을 반환한다.