We all have our pain points when it comes to programming. Mine is using the Math
function with JavaScript. It's a wonderful tool when you know what you're doing but I constantly find myself having to Google what each method means. Off the top of your head, do you know how to generate a random number between 50 and 100? I know you're not required to know these sorts of things but what if we can make it easier on us?
That's why I created totally-random! A utility class to help with random number generation in JavaScript. It's a real-life NPM package I made all by myself that you can install and use right now! Let's me show you how :)
To get started you will need to install the package to your project with the following command:
This will add a node_modules folder to your project (if you didn't have one already) and include totally-random.
Now, let's import it to our JS file:
The first line is the import statement using require
. Right now, I don't know how to implement the ES6 import
statement but that can be something I can add in a future release.
In the next line, we create an instance of the TotallyRandom
class. You can actually see the entire class and its included methods in the repo here.
There's not much to it now but I just wanted to create a working NPM package before I deep dive into adding more methods. The included class methods are probably more than what you need from it, anyways. Let's explore some of them:
You can get a random number up to a positive number and even get a random number down to a negative number. You can also get a random percentage.
Getting a random number within a range of two numbers hasn't been easier! You can even pass an optional third number which will return an array of n randomly selected elements within the range of numbers you provided. Whoa!
You can also get random colors generated! You can see random.color()
will return a random HEX value and random.color('rgb')
will give you a random RGB value.
There are several more methods I'm not going to list here for the sake of length. I hope you guys find totally-random a useful tool to add to your projects to make it just a bit easier.
I will continue to work on this package by adding a more clear README, more random number methods, and maybe I can find a quirky thing or two to add just for fun. Please feel free to contribute!
Top comments (2)
Good job!
I have been having trouble with random numbers too and this looks like it could help me.