mirror of
https://github.com/10h30/odin-javascript-exercises.git
synced 2026-06-05 15:09:09 +09:00
Exercise 12: Provide alternative solution (#459)
* feat(12): improve solution by making it more cleaner * refactor(12): rename `array` to `people` * feat(12): improve explanation of `??=` Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> * feat(12): include both solutions * feat(12): hint to use various array methods * refactor(12): add semicolon Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> * feat(12): use block comments instead of line for readability Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> * refactor(12): remove unnecessary comment Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com> --------- Co-authored-by: MaoShizhong <122839503+MaoShizhong@users.noreply.github.com>
This commit is contained in:
@@ -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,
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user