-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhowOld.js
30 lines (22 loc) · 1.47 KB
/
howOld.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
*
* Philip's just turned four and he wants to know how old he will be in various years in the future such as 2090 or 3044. His parents can't keep up calculating this so they've begged you to help them out by writing a programme that can answer Philip's endless questions.
Your task is to write a function that takes two parameters: the year of birth and the year to count years in relation to. As Philip is getting more curious every day he may soon want to know how many years it was until he would be born, so your function needs to work with both dates in the future and in the past.
Provide output in this format: For dates in the future: "You are ... year(s) old." For dates in the past: "You will be born in ... year(s)." If the year of birth equals the year requested return: "You were born this very year!"
"..." are to be replaced by the number, followed and proceeded by a single space. Mind that you need to account for both "year" and "years", depending on the result.
Good Luck!
*/
// solution
function calculateAge(yearOfBirth, targetYear) {
const age = targetYear - yearOfBirth;
if (age === 0) {
return "You were born this very year!";
} else if (age > 0) {
const yearsOld = age === 1 ? "year" : "years";
return `You are ${age} ${yearsOld} old.`;
} else {
const yearsUntilBorn = Math.abs(age);
const yearsUntilBornText = yearsUntilBorn === 1 ? "year" : "years";
return `You will be born in ${yearsUntilBorn} ${yearsUntilBornText}.`;
}
}