Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Converting humanYears into catYears and dogYears in JavaScript
We need to write a JavaScript function that converts human age into equivalent cat and dog years. The conversion follows specific aging rules for the first two years, then a constant rate afterward.
Problem Statement
Create a function that takes human age in years and returns an array containing human years, cat years, and dog years.
Input:
const humanYears = 15;
Expected Output:
[15, 76, 89]
Age Conversion Rules
The aging calculation follows these rules:
- Year 1: Both cats and dogs age 15 years
- Year 2: Both cats and dogs age an additional 9 years
- Year 3+: Cats age 4 years per human year, dogs age 5 years per human year
Solution Using Loop
const humanYears = 15;
const humanYearsCatYearsDogYears = (humanYears) => {
let catYears = 0;
let dogYears = 0;
for (let i = 1; i <= humanYears; i++) {
if (i === 1) {
catYears += 15;
dogYears += 15;
} else if (i === 2) {
catYears += 9;
dogYears += 9;
} else {
catYears += 4;
dogYears += 5;
}
}
return [humanYears, catYears, dogYears];
};
console.log(humanYearsCatYearsDogYears(humanYears));
[15, 76, 89]
Optimized Mathematical Solution
We can avoid the loop by using direct mathematical calculation:
const humanYearsCatYearsDogYearsOptimized = (humanYears) => {
if (humanYears === 0) return [0, 0, 0];
if (humanYears === 1) return [1, 15, 15];
if (humanYears === 2) return [2, 24, 24];
// First 2 years: 15 + 9 = 24 for both
// Remaining years: (humanYears - 2) * rate
const catYears = 24 + (humanYears - 2) * 4;
const dogYears = 24 + (humanYears - 2) * 5;
return [humanYears, catYears, dogYears];
};
// Test with different ages
console.log(humanYearsCatYearsDogYearsOptimized(1)); // [1, 15, 15]
console.log(humanYearsCatYearsDogYearsOptimized(2)); // [2, 24, 24]
console.log(humanYearsCatYearsDogYearsOptimized(10)); // [10, 56, 64]
console.log(humanYearsCatYearsDogYearsOptimized(15)); // [15, 76, 89]
[1, 15, 15] [2, 24, 24] [10, 56, 64] [15, 76, 89]
Comparison
| Method | Time Complexity | Readability | Performance |
|---|---|---|---|
| Loop Method | O(n) | Good | Slower for large ages |
| Mathematical Method | O(1) | Better | Constant time |
Conclusion
The mathematical approach is more efficient with O(1) complexity, while the loop method is more intuitive for understanding the aging process. Both methods produce identical results for converting human years to pet years.
Advertisements
