forked from TheOdinProject/javascript-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindTheOldest-solution.js
More file actions
40 lines (34 loc) · 1.19 KB
/
findTheOldest-solution.js
File metadata and controls
40 lines (34 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const getAge = function (birth, death) {
if (!death) {
death = new Date().getFullYear();
}
return death - birth;
};
const findTheOldest = function (people) {
return people.reduce((oldest, currentPerson) => {
const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath);
const currentAge = getAge(
currentPerson.yearOfBirth,
currentPerson.yearOfDeath
);
return oldestAge < currentAge ? currentPerson : oldest;
});
};
/* ALTERNATIVE SOLUTION
const getAge = function (person) {
// The nullish coalescing assignment operator
// only does the assignment if the left side is "nullish" (evaluates to undefined or null)
// if the left side has any other value, no assignment happens
// here, we use ??= to set the current year for our subtraction below only if there is no year of death
person.yearOfDeath ??= new Date().getFullYear();
return person.yearOfDeath - person.yearOfBirth;
};
const findTheOldest = function (people) {
const peopleOldestToYoungest = people.toSorted(
(person, nextPerson) => getAge(nextPerson) - getAge(person),
);
const oldestPerson = peopleOldestToYoungest[0];
return oldestPerson;
};
*/
module.exports = findTheOldest;