Get a random number between a range (helper)

function getRandom(min, max) { if (!min) { console.log("getRandom returned 0, no arguments given."); return 0; } else if (!max) { // The minimum acts like the maximum starting frrom 0 return Math.floor(Math.random()*(min+1)); } else { return Math.floor(Math.random()*(max-min+1)+min); } // End of checking arguments } // End of Get Random function // USE CASE //--------------------------- console.log(getRandom(4, 10)); // Outputs -> 6 or 9 for example console.log(getRandom(7)); // Outputs -> 0 or 3 for example console.log(getRandom()); // Outputs -> 0 [and logs "getRandom returned 0, no arguments given."]
Helper function to obtain a number inside a given range (extremes inclusive) and if no maximum value is specified, it returns a value between 0 and the value specified; lastly, if no arguments were given, it returns 0 and logs an error message ─ This snippet is a piece of a JavaScript library I'm working on, you can see it here: https://github.com/luishendrix92/WindowbirdJS

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.