DEV Community

Generating Random Whole numbers in JavaScript in a specific range

Sh Raj on January 14, 2022

Video Documentation :- https://youtu.be/xz3VbIaEG8o Mozilla Developer Network page on this JavaScript Math Object: https://developer.mozilla.o...
Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

About 40% faster:

const getRandomInt = (min, max)=>~~(Math.random()*(max-min+1)+min)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
darkwiiplayer profile image
π’ŽWii πŸ³οΈβ€βš§οΈ

It's faster because it doesn't work; at least not for numbers bigger than what fits in a 32-bit integer ;)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Poorly written spec ;)

Thread Thread
 
darkwiiplayer profile image
π’ŽWii πŸ³οΈβ€βš§οΈ

The spec is wrong 😝

Collapse
 
sh20raj profile image
Sh Raj

Can You Minify this Function also...

function getParameterByName( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
darkwiiplayer profile image
π’ŽWii πŸ³οΈβ€βš§οΈ • Edited

No need, your browser already minified it for you and put it in a class called URLSearchParams 😝

Collapse
 
codingjlu profile image
codingjlu

The "minified" form doesn't behave the same. In negative numbers, the first function is inclusive, while the second one is exclusive.

Run both about 30 times to see what I mean, and pass the values -10, -1.