Created
April 16, 2018 02:24
-
-
Save josnidhin/8451455c6fe35ebfbce125ddcd11701a to your computer and use it in GitHub Desktop.
A simple javascript function to generate a pseudo random hour between a start and end hour
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getRandomHour(startHour, endHour) { | |
if (startHour > 23 || endHour > 23) { | |
throw new Error('Illegal range'); | |
} | |
if (startHour < 0 || endHour < 0) { | |
throw new Error('Illegal range'); | |
} | |
if (startHour === endHour) { | |
return startHour; | |
} | |
let noHours = endHour - startHour, | |
random; | |
if (noHours < 0) { | |
noHours = 24 + noHours; | |
} | |
noHours++; | |
random = Math.floor(Math.random() * (noHours + 1)); | |
console.log(`startHour: ${startHour}, endHour: ${endHour}, noHours: ${noHours}, random: ${random}`); | |
return (startHour + random) % 24; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment