Chance

I am often looking to generate random things in JavaScript. Whether in the browser or in Node, I often find myself looking to generate a random phone number or address or even number with some characteristics. So I created Chance

Chance

I am often looking to generate random things in JavaScript. Whether in the browser or in Node, I often find myself looking to generate a random phone number or address or even number with some characteristics.

Whenever I search the web, I inevitably end up on a StackOverflow article such as this one on how to generate a random number in a specific range.

The relevant bits of which look like:

var min = 1
var max = 6
// Generates random number from 1 to 6
Math.floor(Math.random() * (max - min + 1)) + min

That’s all well and good and certainly works, but I found myself wondering, “Is there no helper library for this?”

So this past weekend I made one. I’m calling it Chance.

It’s open source, freely available, It’s got rich docs and has a whole suite of automated tests.

The same task done above with Chance is far simpler and more readable:

// Generates random number from 1 to 6
chance.natural({ min: 1, max: 6 })

It’s still a work in progress in that I will continue adding generators for other things that people would find useful, but my automated tests and personal testing show that the functionality it currently has is quite solid and ready for use.

And yes I drew the ugly logo myself, I’m clearly a programmer, not a designer.

Published 24 Jun 2013

Scaling and leading engineering and data teams to solve the world's problems
Victor Quinn on Twitter