DEV Community

loading...
Cover image for Rando.js: replacing Math.random()

Rando.js: replacing Math.random()

nastyox1 profile image nastyox Updated on ・3 min read

🙉 What's all the hullabaloo?

There's now a vastly better alternative to JavaScript's built-in Math.random() that will make your life easier. Rando.js helps JavaScript developers code randomness more simply, readably, and securely. Whether you need to find a random int/float between two numbers, pick a random value from an array, choose a random element from your jQuery object, grab a character from a string, toss a coin, or do anything of the like while even preventing repetitions, we've got you covered at a cryptographically strong level. The best part? Our library is extremely lightweight and developer friendly- which means it won't take a toll on your project, and it's uber-simple to implement. Find it online and on GitHub.


⚡ Fast implementation

Step 1: Paste the following script tag into the head of your HTML document:

<script src="https://randojs.com/2.0.0.js"></script>
Enter fullscreen mode Exit fullscreen mode

Or, use npm:

//Install:
npm i @nastyox/rando.js@2.0.0

//Then, paste this at the top of your JavaScript file:
const randojs = require('@nastyox/rando.js'), rando = randojs.rando, randoSequence = randojs.randoSequence;
Enter fullscreen mode Exit fullscreen mode

Step 2: Use any of the commands explained at https://randojs.com/ in the document's JavaScript as you like.


🎉 Examples

   rando()                       //a floating-point number between 0 and 1 (could be exactly 0, but never exactly 1)  
   rando(5)                      //an integer between 0 and 5 (could be 0 or 5)  
   rando(5, 10)                  //a random integer between 5 and 10 (could be 5 or 10)  
   rando(5, "float")             //a floating-point number between 0 and 5 (could be exactly 0, but never exactly 5)  
   rando(5, 10, "float")         //a floating-point number between 5 and 10 (could be exactly 5, but never exactly 10)  
   rando(true, false)            //either true or false  
   rando(["a", "b"])             //{index:..., value:...} object representing a value of the provided array OR false if array is empty  
   rando({a: 1, b: 2})           //{key:..., value:...} object representing a property of the provided object OR false if object has no properties  
   rando($("div"))               //{index:..., value:...} object representing a jQuery element from the provided jQuery element set OR false if the provided jQuery element set does not contain any elements  
   rando("Gee willikers!")       //a character from the provided string OR false if the string is empty. Reoccurring characters will naturally form a more likely return value  
   rando(null)                   //ANY invalid arguments return false  
Enter fullscreen mode Exit fullscreen mode

⇢ Prevent repetitions by grabbing a sequence and looping through it

   randoSequence(5)              //an array of integers from 0 through 5 in random order  
   randoSequence(5, 10)          //an array of integers from 5 through 10 in random order  
   randoSequence(["a", "b"])     //an array of {index:..., value:...} objects representing the values of the provided array in random order  
   randoSequence({a: 1, b: 2})   //an array of {key:..., value:...} objects representing the properties of the provided object in random order  
   randoSequence($("div"))       //an array of {index:..., value:...} objects representing all jQuery elements from the provided jQuery element set in random order  
   randoSequence("Good gravy!")  //an array of the characters of the provided string in random order  
   randoSequence(null)           //ANY invalid arguments return false
Enter fullscreen mode Exit fullscreen mode


If you find this project helpful, please take a second to bookmark the website/leave it a star on GitHub. Thanks everyone.


Discussion (23)

pic
Editor guide
Collapse
mich_cook profile image
mich

This looks quite useful. Given that Math.random() returns a float, what drove your decision to make int the default return type in the numerical instances such as rando(5) and rando(5,10) instead of float? Was it an assumption that most people specifying numbers were looking for ints or something else?

Collapse
nastyox1 profile image
nastyox Author

Thanks! That's a great thought. And yes, that's exactly right. I've seen ints as a much more common use case than floats (excluding [0-1)), so I decided to make that the easier of the two. If you have other thoughts on the project, I'm always interested to hear feedback. You can leave a comment here, DM me on here, or create a pull request on my GitHub.

Collapse
waylonwalker profile image
Waylon Walker • Edited

Hot tip, include language after the leading backticks for codeblocks to get food syntax hilighting.

example

result

randoSequence(5)  
   //a random integer between 5 and 10 (could be 5 or 10)  

   randoSequence(5, 10)  
   // an array of integers from 5 through 10 in random order  

   randoSequence(["eeny", "meeny", "miny", "moe"])  
   // array of {index:..., value:...} objects representing the values of the provided array in random order  

   randoSequence({species: "mouse", blind: true, count: 3})  
   // array of {key:..., value:...} objects representing the properties of the provided object in random order  

   randoSequence($("input"))  
   // array of {index:..., value:...} objects representing a jQuery elements from the provided jQuery element set in random order  

   randoSequence("Good gravy!")  
   // the characters of the provided string in random order  

   randoSequence(null)  
   // ANY invalid arguments return false

EDIT 🤣 corrected hot too to hot tip

Collapse
adam_cyclones profile image
Adam Crockett

food syntax 🌭

Unexpected hotdog.
Collapse
nastyox1 profile image
nastyox Author

Nice tip. Thanks :)

Collapse
krishnakakade profile image
krishna kakade

I added this in my reading list looks interesting 🐱‍🏍❤

Collapse
po5i profile image
Carlos Villavicencio

Looks promising! Is this library a pseudorandom one like Math.random or is it a true random algorithm?

Collapse
mrspartak profile image
Spartak

It is using Math.random, just added sugar around it.
Made a ton prototypes long time ago for such tasks

Array.prototype.getRandom = function () {
    return this[Math.floor(Math.random() * this.length)];
};
console.log( [1, 2, 3].getRandom() )
Collapse
aryanbeezadhur profile image
Aryan Beezadhur

It is pseudorandom, look at the GitHub repo

Collapse
nastyox1 profile image
nastyox Author

It's been getting some attention, so I upgraded it to a cryptographically secure random now. Thanks for being interested in it from the start.

Collapse
daxsoft profile image
Michael Willian Santos

Amazing! I'll study in how to implement it into my projects. Thank you

Collapse
rekreanto profile image
rekreanto

Just love the design of the website <3. The combination of sparseness, clarity and slight aliveness/animation is awesome! randojs.com/

Collapse
nastyox1 profile image
nastyox Author

thanks a bunch!!

Collapse
andygithubchen profile image
Collapse
rwbeast profile image
rwbeast

I had also created a tiny lib for generating random stuff ( integers, floats, hex colors, shuffling an array, unique IDs, etc. ) for personal use. its called kram.js

github.com/rwbeast/kram

Collapse
island_dev profile image
Joel Hyman

Good work! I might use this in a future project.

Collapse
calvinpak profile image
CP

Very nice work!

Collapse
cledilsonweb profile image
Cledilson Nascimento

Very good! randoSequence () is excellent! / Muito bom! randoSequence() é excelente!

Collapse
javierx2010 profile image
Javier Escobar

I think I could use this sometime... Thanks!

Collapse
anshul_gupta profile image
Anshul Gupta

@nastyox
You literally get a domain name to host a website for this project 😂.
I think you have better plans for Rando.js.

Collapse
adam_cyclones profile image
Adam Crockett

If you want an entire replacement of the math std library, I am a bit of a fanboy about this one. mathjs.org/

Collapse
charlygarcia120 profile image
Collapse
louy2 profile image