Skip to content

Exercise 12: Make solution less verbose #459

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion 12_findTheOldest/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ Now that you've reached the final exercise, you should be fairly comfortable get

## Hints
- You should return the whole person object, but the tests mostly just check to make sure the name is correct.
- This can be done with a couple of chained array methods, or by using `reduce`.
- There are many ways of doing this using built-in array methods like `reduce`, or even chaining multiple!
- One of the tests checks for people with no death-date.. use JavaScript's Date function to get their age as of today.
35 changes: 28 additions & 7 deletions 12_findTheOldest/solution/findTheOldest-solution.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
const findTheOldest = function (array) {
return array.reduce((oldest, currentPerson) => {
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,
Expand All @@ -9,11 +16,25 @@ const findTheOldest = function (array) {
});
};

const getAge = function (birth, death) {
if (!death) {
death = new Date().getFullYear();
}
return death - birth;
/* 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;