# Codewars 알고리즘 문제 풀이 (8kyu 95)

dubbsong·2019년 9월 10일
0

#### 문제

• 출생년도부터 해당연도까지 계산하는 함수를 작성한다.

#### 풀이 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.

#### 풀이 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}.;
}
- Math.abs(): 주어진 숫자의 절대값(absolute value)을 반환한다.

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.
오늘도 많이 배웁니다