In: Computer Science
Create a JavaScript program of objects that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use if/else conditional statements to display their approximate age in the selected timeframe. Perform all calculations using an AgeConverter class that accepts the age in years during initialization and has separate properties and methods to calculate and return the age in months, days, hours, and seconds. Include data validation in the class and error handling in the main program by using Node Js as IDE.
JS CODE:
class AgeConverter
{
constructor(age)
{
this.age=age;
}
ageMonths()
{
return this.age*12;
}
ageDays()
{
return Math.ceil(this.ageMonths()*30.44);
}
ageHours()
{
return this.ageDays()*24;
}
ageSeconds()
{
return this.ageHours()*60*60;
}
}
var age=prompt("Enter your age in years: ");
obj=new AgeConverter(age);
console.log("1: Convert age in months");
console.log("2: Convert age in days");
console.log("3: Convert age in hours");
console.log("4: Convert age in seconds");
var choice=prompt("Enter your choice: ");
if(choice==1)
console.log("Age in months: "+obj.ageMonths());
else if(choice==2)
console.log("Age in days: "+obj.ageDays());
else if(choice==3)
console.log("Age in hours: "+obj.ageHours());
else if(choice==4)
console.log("Age in seconds: "+obj.ageSeconds());
else
console.log("Invalid choice");
Sample outputs: