8000 add findOldest Solutions · M-Munk/javascript-exercises@ffa0027 · GitHub
[go: up one dir, main page]

Skip to content

Commit ffa0027

Browse files
committed
add findOldest Solutions
1 parent c0ef28a commit ffa0027

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed

findTheOldest/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Find the Oldest
2+
3+
given an array of objects representing people with a birth and death year, return the oldest person.
4+
5+
## Hints
6+
- You should return the whole person object, but the tests mostly just check to make sure the name is correct.
7+
- this can be done with a couple of chained array methods, or by using `reduce`.
8+
- One of the tests checks for people with no death-date.. use JavaScript's Date function to get their age as of today.
9+
10+

findTheOldest/findTheOldest.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const findTheOldest = function(array) {
2+
return array.reduce((oldest, currentPerson) => {
3+
const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath)
4+
const currentAge = getAge(currentPerson.yearOfBirth, currentPerson.yearOfDeath)
5+
return oldestAge < currentAge ? currentPerson : oldest
6+
})
7+
}
8+
9+
const getAge = function(birth, death) {
10+
if (!death) {
11+
death = new Date().getFullYear();
12+
}
13+
return death - birth;
14+
}
15+
16+
module.exports = findTheOldest

findTheOldest/findTheOldest.spec.js

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
let findTheOldest = require('./findTheOldest')
2+
3+
describe('findTheOldest', function() {
4+
it('finds the oldest person!', function() {
5+
const people = [
6+
{
7+
name: 'Carly',
8+
yearOfBirth: 1942,
9+
yearOfDeath: 1970,
10+
},
11+
{
12+
name: 'Ray',
13+
yearOfBirth: 1962,
14+
yearOfDeath: 2011
15+
},
16+
{
17+
name: 'Jane',
18+
yearOfBirth: 1912,
19+
yearOfDeath: 1941
20+
},
21+
]
22+
expect(findTheOldest(people).name).toEqual('Ray');
23+
});
24+
it('finds the oldest person if someone is still living', function() {
25+
const people = [
26+
{
27+
name: 'Carly',
28+
yearOfBirth: 2018,
29+
},
30+
{
31+
name: 'Ray',
32+
yearOfBirth: 1962,
33+
yearOfDeath: 2011
34+
},
35+
{
36+
name: 'Jane',
37+
yearOfBirth: 1912,
38+
yearOfDeath: 1941
39+
},
40+
]
41+
expect(findTheOldest(people).name).toEqual('Ray');
42+
});
43+
it('finds the oldest person if the OLDEST is still living', function() {
44+
const people = [
45+
{
46+
name: 'Carly',
47+
yearOfBirth: 1066,
48+
},
49+
{
50+
name: 'Ray',
51+
yearOfBirth: 1962,
52+
yearOfDeath: 2011
53+
},
54+
{
55+
name: 'Jane',
56+
yearOfBirth: 1912,
57+
yearOfDeath: 1941
58+
},
59+
]
60+
expect(findTheOldest(people).name).toEqual('Carly');
61+
});
62+
63+
});
64+

0 commit comments

Comments
 (0)
0