Created
June 22, 2019 04:21
-
-
Save lcherone/93043948c3a3b3097cc09f507e1e04e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ageRange = birthYear => { | |
// get age | |
let age = new Date().getFullYear() - birthYear | |
// range of ages | |
const range = [ | |
0, | |
4, | |
9, | |
14, | |
17, | |
24, | |
29, | |
34, | |
39, | |
44, | |
49, | |
54, | |
59, | |
64, | |
69, | |
74, | |
79, | |
84 | |
] | |
// find the closest | |
let closest = range | |
.reduce(function(prev, curr) { | |
return (Math.abs(curr - age) < Math.abs(prev - age) ? curr: prev); | |
}); | |
// find the index of the closest | |
let idx = range.indexOf(closest) | |
// start building result | |
let result = ['Age', closest+1] | |
// add to n or and over for over 85yo | |
if (range[idx+1]) { | |
result.push('to') | |
result.push(range[idx+1]) | |
} else { | |
result.push('and over') | |
} | |
// join it all together now...🍻 | |
return result.join(' ') | |
} | |
'Age 40 to 44' | |
console.log(ageRange(1979)) | |
'Age 85 and over' | |
console.log(ageRange(1900)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment