From 311dd986c5da6dc2888ce95950ea6d2e1a115648 Mon Sep 17 00:00:00 2001 From: pabloabadsanz Date: Wed, 19 Sep 2018 19:25:30 +0200 Subject: [PATCH] Check whether the min specified value is always lower or equals the max one --- Section 2/Anatomy of a Node Application/index.js | 12 ++++++++---- .../Anatomy of a Node Application/lib/math.js | 14 ++++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/Section 2/Anatomy of a Node Application/index.js b/Section 2/Anatomy of a Node Application/index.js index e845556..a591b94 100644 --- a/Section 2/Anatomy of a Node Application/index.js +++ b/Section 2/Anatomy of a Node Application/index.js @@ -33,12 +33,16 @@ app.printAJoke = function(){ // Pick a random number between 1 and the number of jokes var randomNumber = mathLib.getRandomNumber(1,numberOfJokes); + if (randomNumber) { - // Get the joke at that position in the array (minus one) - var selectedJoke = allJokes[randomNumber - 1]; + // Get the joke at that position in the array (minus one) + var selectedJoke = allJokes[randomNumber - 1]; - // Send the joke to the console - console.log(selectedJoke); + // Send the joke to the console + console.log(selectedJoke); + } else { + console.log("No jokes in the file"); + } }; diff --git a/Section 2/Anatomy of a Node Application/lib/math.js b/Section 2/Anatomy of a Node Application/lib/math.js index b9752f5..76c2508 100644 --- a/Section 2/Anatomy of a Node Application/lib/math.js +++ b/Section 2/Anatomy of a Node Application/lib/math.js @@ -13,11 +13,17 @@ var math = {}; // Get a random integer between two integers // Inspired by: http://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript math.getRandomNumber = function(min,max){ - min = typeof(min) == 'number' && min % 1 === 0 ? min : 0; - max = typeof(max) == 'number' && max % 1 === 0 ? max : 0; - return Math.floor(Math.random()*(max-min+1)+min); + + // Check that the min specified value is lower or equals the max one + if (min <= max) { + min = typeof(min) == 'number' && min % 1 === 0 ? min : 0; + max = typeof(max) == 'number' && max % 1 === 0 ? max : 0; + return Math.floor(Math.random()*(max-min+1)+min); + } else { + return false; + } }; // Export the library -module.exports = math; \ No newline at end of file +module.exports = math;