diff --git a/findTheOldest/README.md b/findTheOldest/README.md new file mode 100644 index 0000000..6a2d599 --- /dev/null +++ b/findTheOldest/README.md @@ -0,0 +1,10 @@ +# Find the Oldest + +given an array of objects representing people with a birth and death year, return the oldest person. + +## 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`. +- One of the tests checks for people with no death-date.. use JavaScript's Date function to get their age as of today. + + diff --git a/findTheOldest/findTheOldest.js b/findTheOldest/findTheOldest.js new file mode 100644 index 0000000..80d830b --- /dev/null +++ b/findTheOldest/findTheOldest.js @@ -0,0 +1,16 @@ +const findTheOldest = function(array) { + return array.reduce((oldest, currentPerson) => { + const oldestAge = getAge(oldest.yearOfBirth, oldest.yearOfDeath) + const currentAge = getAge(currentPerson.yearOfBirth, currentPerson.yearOfDeath) + return oldestAge < currentAge ? currentPerson : oldest + }) +} + +const getAge = function(birth, death) { + if (!death) { + death = new Date().getFullYear(); + } + return death - birth; +} + +module.exports = findTheOldest diff --git a/findTheOldest/findTheOldest.spec.js b/findTheOldest/findTheOldest.spec.js new file mode 100644 index 0000000..111c2cd --- /dev/null +++ b/findTheOldest/findTheOldest.spec.js @@ -0,0 +1,64 @@ +let findTheOldest = require('./findTheOldest') + +describe('findTheOldest', function() { + it('finds the oldest person!', function() { + const people = [ + { + name: 'Carly', + yearOfBirth: 1942, + yearOfDeath: 1970, + }, + { + name: 'Ray', + yearOfBirth: 1962, + yearOfDeath: 2011 + }, + { + name: 'Jane', + yearOfBirth: 1912, + yearOfDeath: 1941 + }, + ] + expect(findTheOldest(people).name).toEqual('Ray'); + }); + it('finds the oldest person if someone is still living', function() { + const people = [ + { + name: 'Carly', + yearOfBirth: 2018, + }, + { + name: 'Ray', + yearOfBirth: 1962, + yearOfDeath: 2011 + }, + { + name: 'Jane', + yearOfBirth: 1912, + yearOfDeath: 1941 + }, + ] + expect(findTheOldest(people).name).toEqual('Ray'); + }); + it('finds the oldest person if the OLDEST is still living', function() { + const people = [ + { + name: 'Carly', + yearOfBirth: 1066, + }, + { + name: 'Ray', + yearOfBirth: 1962, + yearOfDeath: 2011 + }, + { + name: 'Jane', + yearOfBirth: 1912, + yearOfDeath: 1941 + }, + ] + expect(findTheOldest(people).name).toEqual('Carly'); + }); + +}); +