DEV Community

loading...
Cover image for My First NPM Package

My First NPM Package

2spacemilk profile image Mark Harless ・2 min read

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:

npm i totally-random

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:

some code

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:

code

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.

code

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!

code

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!

Discussion

pic
Editor guide
Collapse
shriji profile image
Shriji

Good job!

Collapse
shadowtime2000 profile image
shadowtime2000

I have been having trouble with random numbers too and this looks like it could help me.