Skip to content

Instantly share code, notes, and snippets.

@josnidhin
Created April 16, 2018 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josnidhin/8451455c6fe35ebfbce125ddcd11701a to your computer and use it in GitHub Desktop.
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
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