Skip to content

Instantly share code, notes, and snippets.

@lcherone
Created June 22, 2019 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lcherone/93043948c3a3b3097cc09f507e1e04e4 to your computer and use it in GitHub Desktop.
Save lcherone/93043948c3a3b3097cc09f507e1e04e4 to your computer and use it in GitHub Desktop.
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