Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active January 18, 2021 12:04
Show Gist options
  • Save ross-u/8323650c8d737fdf906a008b8c041a87 to your computer and use it in GitHub Desktop.
Save ross-u/8323650c8d737fdf906a008b8c041a87 to your computer and use it in GitHub Desktop.
JS | OOP - Chuckify it - Exercise

JS | OOP


Chuckify it! - Exercise



TLDR;

Using the below script exercise.js, finish the methods getAge(), addJoke() and getRandomJoke() and make the code run properly.

TASKS:


  1. Implement the method addJoke. The method shuould take one string argument and add it to the array of jokes.

  1. Implement the getRandomJoke method using the Math.random. The method should return one random joke from the array of jokes.

  1. Implement the method getAge, which shuould return age in years calculated using the property birthDate. To do this you will have to get the current time and Chuck's birthDate.

  1. Once done, the code on the bottom should run properly and you should be able to add jokes and get random jokes.

Happy coding 🚀

const chuck = {
firstName: 'Chuck',
lastName: 'Norris',
birthDate: new Date('1940-03-10'),
jokes:[
'Chuck Norris counted to infinity... Twice.',
'Chuck Norris is the only man to ever defeat a brick wall in a game of tennis',
],
displayInfo: function() {
console.log('My name is ' + this.firstName + ' ' + this.lastName + ' and I have ' + this.jokes.length + ' jokes!')
},
// TASK 1
addJoke: function(){
// Your code here...
// Hint: you don't need to `return` anything!
},
// TASK 2 - Return random joke from the jokes array
getRandomJoke: function() {
// Your code here...
// Hint: Math.random returns a floating point number e.g. 0.234543
},
// TASK 3
getAge: function() {
// Your code here...
// Hint: to get the current time, you can do: new Date()
// Hint: check what does the getTime() method return
// Hint: to get the birthDate, you can do: this.birthDate
// Hint: you can subtract 2 dates to get the age value in milliseconds :)
},
}
// 4.
chuck.displayInfo();
console.log('getAge', chuck.getAge()) ; // Should return 80 if you are in 2020
chuck.addJoke('Chuck Norris can divide by zero.');
chuck.addJoke('Chuck Norris was once in a knife fight, and the knife lost.');
chuck.addJoke('Chuck Norris doesn\'t Google, he Chuckles');
console.log('getRandomJoke', chuck.getRandomJoke());
console.log('getRandomJoke', chuck.getRandomJoke());
console.log('getRandomJoke', chuck.getRandomJoke());
chuck.displayInfo();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment