Chance is open source software and is released under the
developer and businessfriendly
MIT license.
Usage
bower
It can also be used with Bower
then in the HTML of your app:
<! Load Chance >
<script type="text/javascript" src="bower_components/chance/chance.js"></script>
<script>
// Use Chance
alert(chance.string());
</script>
browser
Easy
Chance instantiates itself onto the window. This means that in the simplest
case you can just include the script tag then use an instance of Chance
immediately.
<script src="chance.js"></script>
<script>
console.log(chance.bool());
</script>
The above snippet would result in either true or false being logged to your
console. Note how the instance is lowercase chance. Uppercase Chance is the
constructor which will create a new instance of Chance.
Intermediate
You can also ignore the global instantiation of Chance and create your own.
This allows you to create multiple instances if you’d like. For convenience, we
also bind Chance to window so it’s accessible globally in the browser at
window.Chance or just Chance.
<script src="chance.js"></script>
<script>
var my_chance = new Chance();
console.log(my_chance.bool());
</script>
Advanced
If you create your own instance of Chance, you can provide your own seed if
you would like to be repeatable or if you’d like a more truly random seed. In
the below example, I am doing an AJAX call to hit Random.org to
retrieve a true random number which I use to seed Chance.
<script src="http://chancejs.com/chance.min.js"></script>
<script src="http://code.jquery.com/jquery1.10.1.min.js"></script>
<script>
var mySeed;
$.get("https://www.random.org/integers/", {num: "1", col: "1", min: "1", max: "1000000000", base: "10", format: "plain", rnd: "new"}, function(randNum) {
mySeed = randNum;
// Instantiate Chance with this truly random number as the seed
var my_seeded_chance = new Chance(mySeed);
console.log(my_seeded_chance.natural());
});
</script>
cli
To use Chance from the command line, install chancecli
globally with:
npm install g chancecli
Then invoke any generator by name followed by options, like so:
$ chance name prefix true
Dr. Georgia Sanchez
$ chance latitude min 12.34 max 56.78
22.01836
More details in the chancecli README
component
It can also be used with Component
component install victorquinn/chancejs
then in the HTML of your app:
<! Load Chance >
<script type="text/javascript" src="components/victorquinnchancejs/chance.js"></script>
<script>
// Use Chance
alert(chance.string());
</script>
node
It can also be used in Node.js
then in your app
// Load Chance
var Chance = require('chance');
// Instantiate Chance so it can be used
var chance = new Chance();
// Use Chance here.
var my_random_string = chance.string();
As of version 0.5.5, the following is also offered as a convenience for getting
an instance of Chance
// Load and instantiate Chance
var chance = require('chance').Chance();
// Use Chance here.
var my_random_string = chance.string();
requirejs
Load Chance with RequireJS
require(['Chance'], function(Chance) {
// Instantiate
var chance = new Chance();
// Then use it:
var my_random_integer = chance.integer();
});
seed
You can also instantiate your own instance of Chance with a known seed. This is
useful for creating repeatable results.
var chance1 = new Chance(12345);
var chance2 = new Chance(12345);
// These yield the same values, in sequence
console.log(chance1.random());
console.log(chance2.random());
Since both copies of Chance had the same seed, they will both generate the same
random number sequence each time they’re called.
This allows for repeatability, if desired.
This is possible because Chance is built atop a Mersenne Twister,
a pseudorandom number generator which produces repeatable results given the same seed.
Optionally provide the seed as a string.
var chance1 = new Chance("foo");
var chance2 = new Chance("bar");
// These will be different
console.log(chance1.random());
console.log(chance2.random());
Optionally provide multiple arguments as the seed.
var chance1 = new Chance("hold", "me", "closer");
var chance2 = new Chance("tony", "danza");
var chance3 = new Chance("hold", "me", "closer");
// These will be different
console.log(chance1.random());
console.log(chance2.random());
// This will be the same as the value from chance1 above
console.log(chance3.random());
function
Instead of providing a seed, which will be used to seed our Mersenne Twister,
you can also specify an arbitrary function to generate random numbers which the
rest of the library will utilize when generating everything else.
A rather simple example, simply using Math.random() instead of our Mersenne Twister
// Use Math.random() instead of our Mersenne Twister
var chance = new Chance(Math.random);
chance.address()
=> '131 Asmun Pike'
chance.address()
=> '261 Pawnaf Highway'
Chance will appear to work just the same, but have a different underlying random
generator.
This function should return any number between 0 and 1.
Basics
bool
chance.bool()
chance.bool({likelihood: 30})
Return a random boolean value (true
or false
).
The default likelihood of success (returning true
) is 50%.
Can optionally specify the likelihood in percent:
chance.bool({likelihood: 30});
=> false
In this case only a 30% likelihood of true
, and a 70% likelihood of false
.
character
chance.character()
chance.character({pool: 'abcde'})
chance.character({alpha: true})
chance.character({casing: 'lower'})
chance.character({symbols: true})
Return a random character.
chance.character();
=> 'v'
By default it will return a string with random character from the following
pool.
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()'
Optionally specify a pool and the character will be generated with characters
only from that pool.
chance.character({pool: 'abcde'});
=> 'c'
Optionally specify alpha for only an alphanumeric character.
chance.character({alpha: true});
=> 'N'
Default includes both upper and lower case. It’s possible to specify one or the
other.
chance.character({casing: 'lower'});
=> 'j'
Note, wanted to call this key just case
but unfortunately that’s a
reserved word in JavaScript for use in a switch statement
Optionally return only symbols
chance.character({symbols: true});
=> '%'
floating
chance.floating()
chance.floating({fixed: 7})
chance.floating({min: 0, max: 100})
Return a random floating point number.
chance.floating();
=> 211920142886.5024
By default it will return a fixed number of at most 4 digits after the decimal.
Note: at most 4 digits. This because, unless we returned trailing zeroes
(which aren’t allowed on the JavaScript float) we can’t guarantee 4 digits after
the decimal. So if random chance comes back with 82383854.2000
then
82383854.2
is what will be returned.
To retrieve a set number of fixed digits after the decimal, provide it as an option.
chance.floating({fixed: 7});
=> 749512327.7447168
As with other number functions, can include a min and/or max.
chance.floating({min: 0, max: 100});
=> 31.9021
Or combine them.
chance.floating({min: 0, max: 100, fixed: 8});
=> 45.92367599
integer
chance.integer()
chance.integer({min: 20, max: 20})
Return a random integer.
range: 9007199254740992 to 9007199254740992
See: Largest number in JavaScript
chance.integer();
=> 1293235
Can optionally provide min and max.
chance.integer({min: 20, max: 20});
=> 7
These min and max are inclusive, so they are included in the range. This means
chance.integer({min: 2, max: 2});
would return either 2, 1, 0, 1, or 2.
// Specific case
2 <= random number <= 2
// General case
min <= random number <= max
natural
chance.natural()
chance.natural({min: 1, max: 20})
Return a natural number.
range: 0 to 9007199254740992
chance.natural();
=> 125019392395
Can optionally provide min and max.
chance.natural({min: 1, max: 20});
=> 14
These are inclusive, so they are included in the range. This means
chance.natural({min: 1, max: 3});
would return either 1, 2, or 3 or:
// Specific case
1 <= random number <= 3
// General case
min <= random number <= max
Natural Number on Wikipedia
string
chance.string()
chance.string({length: 5})
chance.string({pool: 'abcde'})
Return a random string.
chance.string();
=> 'Z&Q78&fqkPq'
By default it will return a string with random length of 520 characters and
will contain any of the following characters.
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()[]'
Can optionally specify a length and the string will be exactly that length.
chance.string({length: 5});
=> 'YN%fG'
Can optionally specify a pool and the string will be generated with characters
only from that pool.
chance.string({pool: 'abcde'});
=> 'cccdeeabedebb'
Of course these options can also be combined.
chance.string({length: 5, pool: 'abcde'});
=> 'cbbdc'
Text
paragraph
chance.paragraph()
chance.paragraph({sentences: 1})
Return a random paragraph generated from sentences populated by semipronounceable
random (nonsense) words.
chance.paragraph();
=> 'Lel fi huepe jupu akse zej ire vesik kojvulom zon is biwuwkef pa. Uv hokivej voh ebu numdogi akolo hik uwlez ta vacev ofdaimi acunetum suvet uhdab ir soglazo ju pafbeb. Pub cezeh fuc kebamnul he ok luumoabi rawkig me fov pin zup biv risugra. Ralpunad apkomgib alnirciw akel wa lus wahfum burog buol vecotihe abadahoj ugolo wovki ucojal fec.'
Default is a paragraph with a random number of sentences from 3 to 7.
Optionally specify the number of sentences in the paragraph.
chance.paragraph({sentences: 1});
=> 'Idefeulo foc omoemowa wahteze liv juvde puguprof epehuji upuga zige odfe igo sit pilamhul oto ukurecef.'
sentence
chance.sentence()
chance.sentence({words: 5})
Return a random sentence populated by semipronounceable random (nonsense) words.
chance.sentence();
=> 'Witpevze mappos isoletu fo res bi geow pofin mu rupoho revzi utva ne.'
The sentence starts with a capital letter, and ends with a period.
Default is a sentence with a random number of words from 12 to 18.
This length is chosen as the default as it works out to the average English
sentence is in that range.
Optionally specify the number of words in the sentence.
chance.sentence({words: 5});
=> 'Waddik jeasmov cakgilta ficub up.'
syllable
chance.syllable()
Return a semispeakable syllable, 2 or 3 letters
chance.syllable();
=> 'fop'
The syllable is returned in all lower case.
A syllable generally alternates between vowel and consanant and is used as the
core building block for a word.
word
chance.word()
chance.word({syllables: 3})
chance.word({length: 5})
Return a semipronounceable random (nonsense) word.
chance.word();
=> 'bappada'
The word is returned in all lower case.
Default is a word with a random number of syllables from 1 to 3.
This length is chosen as it works out to the average word length of ~56 chars
which seems about right.
Can optionally specify a number of syllables which the word will have.
Note these are not syllables in the strict language definition of the word, but
syllables as we’ve defined here which is 2 or 3 characters, mostly alternating
between vowel and consanant. This is the about the best we can do with purely
random generation.
chance.word({syllables: 3});
=> 'tavnamgi'
Can optionally specify a length and the word will obey that bounding.
chance.word({length: 5});
=> 'ralve'
In this case these 2 options are mutually exclusive, that is they cannot be
combined as they often make no sense. It wouldn’t be possible to have a word
with 7 syllables and a length of 5 or a length of 30 but 2 syllables.
Therefore, if both are specified, an Exception will be thrown so the Developer
can handle their broken case.
chance.word({length: 5, syllables: 20});
=> new RangeError("Chance: Cannot specify both syllables AND length.");
Person
age
chance.age()
chance.age({type: 'child'})
Generate a random age
Default range is between 1 and 120
Optionally specify one of a handful of enumerated age types:
chance.age({type: 'child'});
=> 9
Allowed types are: child
, teen
, adult
, senior
birthday
chance.birthday()
chance.birthday({string: true})
chance.birthday({type: 'child'})
Generate a random birthday
chance.birthday();
=> Fri Aug 16 1985 00:00:00 GMT0400 (EDT)
By default, returns an actual JavaScript Date object.
Optionally specify it be returned as a string.
chance.birthday({string: true});
=> '4/1/1968'
By default returns in MM/DD/YYYY format. Can specify DD/MM/YYYY as follows:
chance.birthday({string: true, american: false});
=> '28/6/1993'
For more complex date formats, use the Moment library.
Can also specify the type, same types as with age.
chance.birthday({type: 'child'});
=> Sat Sep 08 2001 00:00:00 GMT0400 (EDT)
You can also compose with chance.year
for interesting combinations. For example, let’s say we want to get the birthdays of some renaissance artists (born between 1450 and 1500). We can generate a year and then get a birthday from that year:
var year = chance.year({ min: 1450, max: 1500 });
chance.birthday({ year: year });
=> Wed Aug 27 1484 11:24:14 GMT0400 (EDT)
// Could be simplified down to one line
chance.birthday({ year: chance.year({ min: 1450, max: 1500 }) });
=> Fri Nov 26 1469 09:17:13 GMT0500 (EST)
cpf
chance.cpf()
Generate a random Brazilian tax id.
chance.cpf();
=> '607.116.89962'
first
chance.first()
Generate a random first name
Chance.first();
=> 'Leila'
Optionally specify a gender to limit first names to that gender
Chance.first({ gender: "female" });
=> 'Emma'
gender
chance.gender()
Generate a random gender
Chance.gender();
=> 'Female'
last
chance.last()
Generate a random last name
name
chance.name()
chance.name({middle: true})
chance.name({middle_initial: true})
chance.name({prefix: true})
Generate a random name
chance.name();
=> 'Dafi Vatemi'
Optionally include the middle name
chance.name({ middle: true });
=> 'Nelgatwu Powuku Heup'
Optionally include the middle initial
chance.name({ middle_initial: true });
=> 'Ezme I Iza'
Optionally include the prefix
chance.name({ prefix: true });
=> 'Doctor Suosat Am'
Optionally include the suffix
chance.name({ suffix: true });
=> 'Fanny Baker Esq.'
Optionally specify a gender
chance.name({ gender: "male" });
=> "Patrick Copeland"
prefix
chance.prefix()
chance.prefix({full: true})
Generate a random name prefix
chance.prefix();
=> 'Mrs.'
By default, returns the shorter version.
Optionally get back the full version.
chance.prefix({ full: true });
=> 'Mister'
Optionally specify a gender. Valid options are male
, female
, or all
(the default).
chance.prefix({ gender: "male" });
=> 'Mr.'
chance.prefix({ gender: "female" });
=> 'Miss'
To maintain legacy support, this also responds to chance.name_prefix().
ssn
chance.ssn()
Generate a random social security number.
chance.ssn();
=> '411900070'
Optionally provide option of getting only the last four
chance.ssn({ ssnFour: true });
=> '2938'
Optionally specify dashes be removed
chance.ssn({ dashes: false });
=> '293839295'
suffix
chance.suffix()
chance.suffix({full: true})
Generate a random name suffix
chance.suffix();
=> 'Sr.'
By default, returns the shorter version.
Optionally get back the full version.
chance.suffix({ full: true });
=> 'Juris Doctor'
To maintain legacy support, this also responds to chance.name_suffix().
Mobile
android_id
chance.android_id()
Return a random GCM registration ID.
chance.android_id()
=> 'APA91HHQyPlWqV2Nu61LRs41eE4vrR4bHLKTs0Dh5nDLopcWZotLw77NEoJyADNJiq6cwY0jMM02y8aacLs6fe2_ynweFjZJVVevKON32826vEFoayyThU342YEUY9pCScU_n73yRNSOlTk5W6iPtrDkQ3a6_BvOxRbSYi3E6QEY0ZuIQF0'
apple_token
chance.apple_token()
Return a random Apple Push Token
chance.apple_token()
=> 'b50edac575bfba07dd019b28b2af7189a3ddda17c806ef14a9abbfd00533f67e'
bb_pin
chance.bb_pin()
Return a random BlackBerry Device PIN
chance.bb_pin()
=> '985de771'
wp7_anid
chance.wp7_anid()
Return a random Windows Phone 7 ANID
chance.wp7_anid()
=> 'A=3FC2491A0E0C5AB7824B2F60DCE4DB02&E=4e7&W=6'
wp8_anid2
chance.wp8_anid2()
Return a random Windows Phone 8 ANID2
chance.wp8_anid2()
=> 'OGI5ODk0MmNkZGI2OGE3YzAwODE1Y2NiYTc4MzEzZjM='
Web
color
chance.color()
chance.color({format: 'hex'})
chance.color({grayscale: true})
chance.color({casing: 'upper'})
Return a random color.
chance.color()
=> '#79c157'
Colors have four base types: hex
, shorthex
, rgb
, 0x
These are the kinds usable in HTML or CSS. The type can optionally be specified
chance.color({format: 'hex'})
=> '#d67118'
chance.color({format: 'shorthex'})
=> '#60f'
chance.color({format: 'rgb'})
=> 'rgb(110,52,164)'
chance.color({format: '0x'})
=> '0x67ae0b'
Can optionally specify that only grayscale colors be generated
chance.color({grayscale: true})
=> '#e2e2e2'
Optionally specify casing to get only uppercase letters in the color
chance.color({casing: 'upper'})
=> '#29CFA7'
domain
chance.domain()
chance.domain({tld: 'com'})
Return a random domain with a random tld.
chance.domain()
=> 'onaro.net'
Optionally specify a tld and the domain will be random but the tld will not.
chance.domain({tld: 'ie'})
=> 'gotaujo.ie'
email
chance.email()
chance.email({domain: "example.com"})
Return a random email with a random domain.
chance.email()
=> 'kawip@piklojzob.gov'
Optionally specify a domain and the email will be random but the domain will not.
chance.email({domain: 'example.com'})
=> 'giigjom@example.com'
fbid
chance.fbid()
Return a random Facebook id, aka fbid.
chance.fbid()
=> "1000039460258605"
google_analytics
chance.google_analytics()
Return a random Google Analytics tracking code. Takes the form 'UA12345601'
chance.google_analytics()
=> 'UA38455517'
hashtag
chance.hashtag()
Return a random hashtag. This is a string of the form ‘#thisisahashtag’.
chance.hashtag()
=> '#dichumwa'
ip
chance.ip()
Return a random IP Address.
chance.ip()
=> '153.208.102.234'
ipv6
chance.ipv6()
Return a random IPv6 Address.
chance.ipv6()
=> 'db2f:6123:f99e:00f7:a76e:7f68:9f91:bb08'
klout
chance.klout()
Return a random Klout score. Range 199.
tld
chance.tld()
Return a random tld (Top Level Domain) from the set:
['com', 'org', 'edu', 'gov', 'uk', 'net', 'io']
Note, these do not start with a period.
url
chance.url()
chance.url({domain: 'www.socialradar.com'})
chance.url({path: 'images'})
chance.url({extensions: ['gif', 'jpg', 'png']})
Return a random url.
chance.url()
=> 'http://vanogsi.io/pateliivi'
Optionally specify a domain and the url will be random but the domain will not.
chance.url({domain: 'www.socialradar.com'})
=> 'http://www.socialradar.com/hob'
Optionally specify a path and it will be obeyed.
chance.url({path: 'images'})
=> 'http://tainvoz.net/images'
Optionally specify an array of extensions and one will be picked at random.
chance.url({extensions: ['gif', 'jpg', 'png']})
=> 'http://vagjiup.gov/udmopke.png'
Location
address
chance.address()
chance.address({short_suffix: true})
Generate a random street address
chance.address();
=> '5447 Bazpe Lane'
Optionally mandate that it return a short suffix
chance.address({short_suffix: true});
=> '536 Baner Rd'
altitude
chance.altitude()
chance.altitude({ fixed: 7 })
chance.altitude({ max: 1000 })
Generate a random altitude, in meters.
chance.altitude()
=> 1863.21417
By default, includes 5 digits of accuracy after the decimal. Can override with the fixed
option.
chance.altitude({ fixed: 7 })
=> 6897.8978386
By default, max of 8848m (height of Mount Everest), but this can be overridden with the max
option.
chance.altitude({ max: 1000 })
=> 890.20665
areacode
chance.areacode()
Generate a random area code
chance.areacode()
=> '(526)'
Note, this is a US area code, we have little support for internationalization
at this time. Hope to fix that in the future!
city
chance.city()
Generate a random city name
chance.city();
=> 'Cowotba'
coordinates
chance.coordinates()
chance.coordinates({fixed: 2})
Generate random coordinates, which are latitude and longitude, comma separated.
chance.coordinates();
=> "29.52974, 24.52815"
By default includes 5 fixed digits after decimal, can specify otherwise.
chance.coordinates({fixed: 2});
=> "49.16, 68.81"
country
chance.country()
chance.country({ full: true })
Return a random country.
chance.country();
=> 'LT'
By default, returns only the 2 letter ISO 31661 code for the country.
Optionally specify that it ought to return a full country name.
chance.country({ full: true });
=> 'Venezuela'
depth
chance.depth()
chance.depth({ fixed: 2 })
chance.depth({ min: 1000 })
Generate a random depth, in meters. Depths are always negative
chance.depth()
=> 2126.95039
By default, includes 5 digits of accuracy after the decimal. Can override with the fixed
option.
chance.depth({ fixed: 2 })
=> 1542.11
By default, maximum (or minimum depending on your frame of reference) depth of 2550 (depth of the Mariana Trench), but this can be overridden with the min
option.
chance.depth({ min: 1000 })
=> 718.41976
geohash
chance.geohash()
chance.geohash({ length: 5 })
Generate a random geohash. More details on what a geohash is.
chance.geohash()
=> 'h9xhn7y'
By default, includes 7 characters of accuracy. Can override with the length
option.
chance.geohash({ length: 5 })
=> 'dr0kr'
latitude
chance.latitude()
chance.latitude({fixed: 7})
Generate a random latitude.
chance.latitude();
=> 57.99514
range: 90 to 90
By default includes 5 fixed digits after decimal, can specify otherwise.
chance.latitude({fixed: 7});
=> 29.6443133
By default includes entire range of allowed latitudes, can specify a min and/or max to bound it
chance.latitude({min: 38.7, max: 38.9});
=> 38.82358
longitude
chance.longitude()
chance.longitude({fixed: 7})
Generate a random longitude.
chance.longitude();
=> 149.41549
range: 180 to 180
By default includes 5 fixed digits after decimal, can specify otherwise.
chance.longitude({fixed: 7});
=> 51.4549925
By default includes entire range of allowed longitudes, can specify a min and/or max to bound it
chance.longitude({min: 78, max: 77});
=> 77.22644
phone
chance.phone()
chance.phone({ country: "fr" })
chance.phone({ country: "fr", mobile: true })
Generate a random phone
chance.phone();
=> '(494) 9272152'
By default conforms to NANP for a proper US phone number.
Optionally specify a country.
chance.phone({ country: 'fr' });
=> '01 60 44 92 67'
Note, at current we only have support for 'us'
, 'uk'
, or 'fr'
for countries.
For uk
and fr
, optionally specify a mobile phone.
chance.phone({ country: 'uk', mobile: true });
=> '07624 321221'
postal
chance.postal()
Return a Canadian Postal code. Returned postal code is valid with respect to the Postal District (first character) and format only.
chance.postal();
=> 'R1S 3F4'
province
chance.province()
chance.province({full: true})
Return a random province.
chance.province();
=> 'ON'
By default, returns only the 2 letter abbreviation for province.
Optionally specify that it ought to return a full province name.
chance.province({full: true});
=> 'Nova Scotia'
state
chance.state()
chance.state({ full: true })
chance.state({ territories: true })
chance.state({ armed_forces: true })
chance.state({ us_states_and_dc: false })
Return a random state.
By default, returns only the 2 letter abbreviation for state.
Optionally specify that it ought to return a full state name.
chance.state({ full: true });
=> 'Florida'
Optionally add U.S. Territories (‘American Samoa’, ‘Federated States of Micronesia’, ‘Guam’, ‘Marshall Islands’, ‘Northern Mariana Islands’, ‘Puerto Rico’, ‘Virgin Islands, U.S.’) to the mix of randomly selected items:
chance.state({ territories: true, full: true })
=> 'Guam'
Optionally add Armed Forces to the list as well:
chance.state({ armed_forces: true, full: true })
=> 'Armed Forces Pacific'
For all U.S. states, territories, and armed forces, specify all of them:
chance.state({ armed_forces: true, territories: true })
=> 'NY'
For just territories or armed forces, specify that it ought not return U.S. states:
chance.state({ territories: true, us_states_and_dc: false })
=> 'PR'
street
chance.street()
Generate a random street
chance.street();
=> 'Tesca Circle'
Optionally mandate that it return a short suffix
chance.street({short_suffix: true});
=> 'Jiled St'
zip
chance.zip()
chance.zip({plusfour: true})
Generate a random (U.S.) zip code.
Can optionally specify that it ought to return a Zip+4:
chance.zip({plusfour: true});
=> '010351838'
Time
For more complex time manipulation, Moment is
strongly recommended. It would be out of this library's core competency to try and
provide date objects of all formats
ampm
chance.ampm()
Return am or pm. Very simple.
date
chance.date()
chance.date({string: true})
chance.date({string: true, american: false})
chance.date({year: 1983})
Generate a random date
chance.date();
=> Sat Apr 09 2072 00:00:00 GMT0400 (EDT)
By default, returns an actual Date object
Can optionally specify that a date be returned as a string
chance.date({string: true});
=> "5/27/2078"
This will return a date string of the format MM/DD/YYYY.
Now of course MM/DD/YYYY is the “American” date method, but it’s the default
because there isn’t much support for internationalization here yet. Further,
it’s the format used by Facebook and other services for birthdays and
other nonDate object dates.
However, we support returning dates in DD/MM/YYYY format as well when requesting
a date by a string and passing american: false
.
chance.date({string: true, american: false});
=> "13/2/2017"
If you want richer control over date format, strongly suggest using the
Moment library. Our formatting is very minimalist, and it’s out of our
core competency to offer dates in a myriad of formats.
Can optionally specify defaults for any of day, month, or year.
chance.date({year: 1983});
=> Wed May 04 1983 00:00:00 GMT0400 (EDT)
chance.date({month: 0});
=> Tue Jan 18 2084 00:00:00 GMT0500 (EST)
chance.date({day: 21});
=> Sun Oct 21 2103 00:00:00 GMT0400 (EDT)
A random date is generated, but the default you specify is kept constant.
Note, month is 0indexed. This is a carryover from the core JavaScript
Date object which we use internally to generate the date. We
considered
hammertime
chance.hammertime()
Generate a random hammertime.
chance.hammertime();
=> 2273327300317
Hammertime is the name given to a Unix time with
milliseconds. Which is the same as saying the number of milliseconds since 1970. It has
finer granularity than a normal Unix timestamp and thus is often used in realtime
applications.
According to startup lore, Hammertime was coined by a startup whose founder had an
interesting interaction with M.C. Hammer. There was no name given to “Unix time with
milliseconds” and while brainstorming ideas (because Unix time with milliseconds is
a confusing mouthful), someone suggested Hammertime and it stuck.
hour
chance.hour()
chance.hour({twentyfour: true})
Generate a random hour
By default, returns an hour from 1 to 12 for a standard 12hour clock.
Can optionally specify a full twentyfour.
chance.hour({twentyfour: true});
=> 21
This will return an hour from 1 to 24.
millisecond
chance.millisecond()
Generate a random millisecond
chance.millisecond();
=> 729
By default, returns a millisecond from 0 to 999. Idea is for generating a clock time.
minute
chance.minute()
Generate a random minute
By default, returns a minute from 0 to 59. Idea is for generating a clock time.
month
chance.month()
Generate a random month.
chance.month();
=> 'January'
By default, returns just the full name.
Optionally specify raw to get the whole month object consisting of name,
short_name, and numeric.
chance.month({raw: true});
=> {name: 'October', short_name: 'Oct', numeric: '10'}
second
chance.second()
Generate a random second
By default, returns a second from 0 to 59. Idea is for generating a clock time.
timestamp
chance.timestamp()
Generate a random timestamp. This is a standard Unix time, so a random number of
seconds since January 1, 1970.
chance.timestamp();
=> 576556683
year
chance.year()
chance.year({min: 1900, max: 2100})
Generate a random year
By default, min is the current year and max is 100 years greater than min.
This is returned as a string. If for some reason you need it numeric, just
parse it:
parseInt(chance.year());
=> 2042
Optionally specify min, max, or both to limit the range.
chance.year({min: 1900, max: 2100});
=> '1983'
Finance
cc
chance.cc()
chance.cc({type: 'Mastercard'})
Generate a random credit card number. This card number will pass the
Luhn algorithm so it looks like a legit card.
chance.cc();
=> '6304038511073827'
Optionally specify a particular type of card to return:
chance.cc({type: 'Mastercard'});
=> '5171206237468496'
The type can be specified by the long name, or by the short name:
chance.cc({type: 'mc'});
=> '5103820202214116'
The types are enumerated below.
cc_type
chance.cc_type()
chance.cc_type({raw: true})
Return a random credit card type.
chance.cc_type();
=> 'Visa'
Default returns just the name. To return the entire object (consisting of name,
short name, numeric prefix, and length), specify so with the raw flag.
chance.cc_type({raw: true});
=> {name: 'Discover Card', short_name: 'discover', prefix: '6011', length: 16}
The available types are (name  short_name):
 American Express  amex
 Bankcard  bankcard
 China UnionPay  chinaunion
 Diners Club Carte Blanche  dccarte
 Diners Club enRoute  dcenroute
 Diners Club International  dcintl
 Diners Club United States & Canada  dcusc
 Discover Card  discover
 InstaPayment  instapay
 JCB  jcb
 Laser  laser
 Maestro  maestro
 Mastercard  mc
 Solo  solo
 Switch  switch
 Visa  visa
 Visa Electron  electron
currency
chance.currency()
Generate a random currency.
chance.currency();
=> { code: "TVD", name: "Tuvalu Dollar" }
currency_pair
chance.currency_pair()
Generate a currency pair. Handy for simulating currency conversions. Guaranteed to return a unique pair (and not the same currency twice).
chance.currency_pair();
=> [{ code: "ALL", name: "Albania Lek" }, { code: "ZWD", name: "Zimbabwe Dollar" }]
dollar
chance.dollar()
chance.dollar({max: 250})
Return a random dollar amount.
chance.dollar();
=> "$2560.27"
chance.dollar();
=> "$750.99"
By default returns dollar amount no larger than 10000. Optionally specify
the max to make it larger (or smaller).
chance.dollar({max: 20});
=> "$15.23"
chance.dollar({max: 10000000})
=> "$5051205.49"
exp
chance.exp()
chance.exp({raw: true})
Generate a random credit card expiration.
chance.exp();
=> '10/2020'
Optionally specify that a raw object be returned rather than a string
chance.exp({raw: true});
=> {month: '11', year: '2017'}
exp_month
chance.exp_month()
chance.exp_month({future: true})
Generate a random credit card expiration month.
chance.exp_month();
=> '01'
Optionally specify that it must be a later month than the current month.
chance.exp_month({future: true});
=> '10'
So if called in June, this would return a random month from July  Dec. If
called in October, would return November or December.
This because many credit card sandboxes require an expiration date later
than the current date so it’s necessary when generating an expiration with the
current year to generate a month later than the current month.
exp_year
chance.exp_year()
Generate a random credit card expiration year.
chance.exp_year();
=> '2018'
Returns a random year between today and 10 years in the future.
Helpers
capitalize
chance.capitalize(string)
Capitalize the first letter of a word
chance.capitalize('bread')
=> 'Bread'
mixin
chance.mixin(<Object>)
Mixins are a very powerful way to extend Chance to fit the needs of your
specific application.
First, if you are thinking of using a mixin for Chance, please consider first
whether your use is something from which others may benefit. If so, please
submit a pull request rather than using a mixin!
Spread the love and give everyone the benefit of your awesome generator :)
Now, that said, there are bound to be times when you want to generate something
random that is specific to your application but not widely applicable. Enter
mixins!
Chance mixins allow you to add oneoff methods to Chance which you can
use later.
For example, let’s say I have a user object which consists of first, last,
and email.
var user = {
first: 'John',
last: 'Smith',
email: 'john@aol.com'
};
Let’s say I want to be able to randomly generate these user objects.
This is not the type of thing which would be widely applicable as it’s specific
to my application so it’s perfect for a mixin!
To create a mixin, build an object whose keys are the names of the methods, and
whose values are the functions to be called.
Note: Within each function, you will have access to chance
itself!
For example, to create a user
mixin:
chance.mixin({
'user': function() {
return {
first: chance.first(),
last: chance.last(),
email: chance.email()
};
}
});
// Then you can call your mixin
chance.user();
=> {first: 'Eli', last: 'Benson', email: 'gembibuj@dugesan.com'}
Mixins can even include other mixins!
For example, to “extend” the user object:
chance.mixin({
'user': function () {
return {
first: chance.first(),
last: chance.last(),
email: chance.email()
};
},
'social_user': function () {
var user = chance.user();
user.network = chance.pick(['facebook', 'twitter']);
return user;
}
});
So we have a second mixin here, social_user
which is using the user
mixin
and adding to it! Note, these mixins can be defined in any order on the object
if both declared at once.
pad
chance.pad(number, width)
chance.pad(number, width, padder)
Pad a number with some string until it reaches a desired width.
By default, chance.pad()
will pad with zeroes. For example, to zeropad
numbers such that the outcome width is 5, do the following.
chance.pad(45, 5)
=> '00045'
chance.pad(284, 5)
=> '00284'
chance.pad(82843, 5)
=> '82843'
Notice how every item returned is a string with leading zeroes until the width
is 5 for each one.
Can optionally specify a character if the desire is to pad with something other
than zero.
chance.pad(81, 5, 'Z')
=> 'ZZZ81'
chance.pad(692, 5, 'Z')
=> 'ZZ692'
chance.pad(52859, 5)
=> '52859'
pick
chance.pick(array)
chance.pick(array, count)
Given an array, pick a random element and return it
chance.pick(['alpha', 'bravo', 'charlie', 'delta', 'echo']);
=> 'delta'
Optionally specify a count
of elements to return, which returns an array
populated by some random group of those elements of the size specified
chance.pick(['alpha', 'bravo', 'charlie', 'delta', 'echo'], 3);
=> ['delta', 'alpha', 'echo']
// Another example just to help with clarity
chance.pick(['alpha', 'bravo', 'charlie', 'delta', 'echo'], 3);
=> ['echo', 'alpha', 'delta']
set
chance.set(key, value)
Used for overriding the default data used by Chance.
For example, if instead of the default set of last names (which were pulled from the U.S. census data and therefore obviously American biased), you could replace the data for the first names with something more suited to your task. For example, if you want instead to pick from last names of houses in A Song of Ice and Fire, you could do something like:
chance.set('lastNames', ['Arryn', 'Baratheon', 'Bolton', 'Frey', 'Greyjoy', 'Lannister', 'Martell', 'Stark', 'Targaryen', 'Tully', 'Tyrell']);
// then
chance.last()
=> 'Lannister'
This is very handy for internationalization.
Available keys for datasets to override: firstNames
, lastNames
, provinces
, us_states_and_dc
, territories
, armed_forces
, street_suffixes
, months
, cc_types
, currency_types
shuffle
chance.shuffle(array)
Given an array, scramble the order and return it.
chance.shuffle(['alpha', 'bravo', 'charlie', 'delta', 'echo']);
=> ['echo', 'delta', 'alpha', 'charlie', 'bravo']
Miscellaneous methods
dice
chance.d4()
chance.d6()
chance.d8()
chance.d10()
chance.d12()
chance.d20()
chance.d30()
chance.d100()
Return a value equal to the roll of a die.
chance.d20();
=> 13
chance.d6();
=> 4
These are just wrappers around natural() but are convenient for use by games.
guid
chance.guid()
Return a random guid.
chance.guid();
=> 'f0d8368d85e254fb73c42d60374295e3'
hash
chance.hash()
chance.hash({length: 25})
chance.hash({casing: 'upper'})
Return a random hex hash
chance.hash()
=> 'e5162f27da96ed8e1ae51def1ba643b91d2581d8'
By default, the hash is lowercase and 40 hex characters long (same as a git
commit hash).
Optionally specify a length
chance.hash({length: 15})
=> 'c28f57cb599ada4'
Optionally specify casing to get a hash with only uppercase letters
rather than the default lowercase
chance.hash({casing: 'upper'})
=> '3F2EB3FB85D88984C1EC4F46A3DBE740B5E0E56E'
hidden
chance.cc_types()
chance.mersenne_twister()
chance.mersenne_twister(12345)
chance.months()
chance.name_prefixes()
chance.provinces()
chance.states()
chance.street_suffix()
chance.street_suffixes()
These aren’t really hidden per se, but just utility methods intended to be used
internally but exposed externally in case they’re useful to anyone.
// Return the list of cc types
chance.cc_types()
=> [{name: "American Express", short_name: 'amex', prefix: '34', length: 15}, ...]
// Return a new Mersenne Twister
chance.mersenne_twister()
=> [object Object] // An instance of a Mersenne Twister
// Optionally provide a seed for that twister
chance.mersenne_twister(12345)
=> [object Object] // An instance of a twister with seed 12345
// Return our list of name prefixes
chance.months();
=> [{name: 'January', short_name 'Jan', numeric: '01'}, ...]
// Return our list of name prefixes
chance.name_prefixes();
=> [{name: 'Doctor', abbreviation: 'Dr.'}, {name: 'Miss', abbreviation: 'Miss'}, ...]
// Return the list of provinces
chance.provinces();
=> [{name: 'Alberta', abbreviation: 'AB'}, {name: 'British Columbia', abbreviation: 'BC'}, ...]
// Return the list of states
chance.states();
=> [{name: 'Alabama', abbreviation: 'AL'}, {name: 'Alaska', abbreviation: 'AK'}, ...]
// Return a random street suffix
chance.street_suffix();
=> {name: 'Street', abbreviation: 'St'}
// Return the list of street suffixes
chance.street_suffixes();
=> [{name: 'Avenue', abbreviation: 'Ave'}, {name: 'Boulevard', abbreviation: 'Blvd'}, ...]
n
chance.n(chance.email, 5)
chance.n(chance.email, 5, { domain: "socialradar.com" })
Provide any function that generates random stuff (usually another Chance function) and a number and n()
will generate an array of items with a length matching the length you specified.
For example, to generate 5 email addresses:
chance.n(chance.email, 5);
=> [ 'nese@me.gov',
'tukvogi@novew.co.uk',
'worzi@jotok.edu',
'wicumafom@lalu.edu',
'hifebwo@abecusa.com' ]
Any options that would be sent to the random function can be added following the number.
For example, chance.email()
has options which can be specified, so you can generate 5 emails with a known domain as follows:
chance.n(chance.email, 5, { domain: "socialradar.com" })
=> [ 'nuvvu@socialradar.com',
'icolul@socialradar.com',
'rig@socialradar.com',
'ca@socialradar.com',
'uc@socialradar.com' ]
Note, these items are not guaranteed to be unique. If that is the intent, see chance.unique()
normal
chance.normal()
chance.normal({mean: 100})
chance.normal({mean: 100, dev: 15})
Return a normallydistributed random variate.
chance.normal()
=> 0.4244767651300604
By default this starts with a mean of 0
and a standard deviation of 1
which
is the standard normal distribution.
Optionally specify a mean and/or deviation.
// Notice, since no deviation was specified, using the default of `1`
chance.normal({mean: 100})
=> 99.68352269988522
// For example, to get a random IQ (which by definition has a mean of 100
// and a standard deviation of 15)
chance.normal({mean: 100, dev: 15})
=> 85.11040121833615
Used in combination with the above generators, this can be an extremely powerful
way to get more realistic results as often “pure random” results fail to
approximate the real world.
radio
chance.radio()
Generate a random radio call sign.
chance.radio();
=> 'KCXW'
Optionally specify a side of the Mississippi River to limit stations to that side.
See K and W for more details
chance.radio({side: 'east'});
=> 'WKOQ'
chance.radio({side: 'east'});
=> 'WNOW'
rpg
chance.rpg('#d#')
chance.rpg('#d#', {sum: true})
Given an input looking like #d#, where the first # is the number of dice to
roll and the second # is the max of each die, returns an array of dice values.
chance.rpg('3d10');
=> [1, 6, 9]
chance.rpg('5d6');
=> [3, 1, 2, 5, 2]
Optionally specify a sum be returned rather than an array of dice.
chance.rpg('3d10', {sum: true});
=> 14
tv
chance.tv()
chance.tv({side: 'west'})
Generate a TV station call sign. This is an alias for radio()
since they both
follow the same rules.
chance.radio();
=> 'WXTY'
Optionally specify a side of the Mississippi River to limit stations to that side.
chance.radio({side: 'west'});
=> 'KCYL'
chance.radio({side: 'west'});
=> 'KQDV'
unique
chance.unique(chance.state, 5)
chance.unique(chance.state, 5, { comparator: func })
Provide any function that generates random stuff (usually another Chance function) and a number and unique()
will generate a random array of unique (not repeating) items with a length matching the one you specified.
chance.unique(chance.state, 5);
=> ["SC", "WA", "CO", "TX", "ND"]
This is helpful when there are a limited number of options and you want a bunch but want to ensure each is different.
Optionally specify the comparator used to determine whether a generated item is in the list of already generated items. By default the comparator just checks to see if the newly generated item is in the array of already generated items. This works for most simple cases (such as chance.state()
) but will not work if the generated item is an object (because the Array.prototype.indexOf()
method will not work on an object since 2 objects will not be strictly equal, ===
, unless they are references to the same object).
chance.unique(chance.currency, 2, {
comparator: function(err, val) {
return arr.reduce(function(acc, item) {
return acc  (item.code === val.code);
}, false);
}
});
=> [{ code: "KYF", name: "Cayman Islands Dollar" }, { code: "CDF", name: "Congo/Kinshasa Franc" }]
Note, there could be cases where it is impossible to generate the unique number. For example, if you choose chance.state
as shown above as the random function and want say, 55 uniques, Chance will throw a RangeError because it is impossible to generate 55 uniques because there are only 51 states in the available pool (50 states plus the District of Columbia).
chance.unique(chance.state, 55);
=> RangeError: Chance: num is likely too large for sample set
weighted
chance.weighted(['a', 'b'], [100, 1])
chance.weighted(['a', 'b', 'c', 'd'], [1, 2, 3, 4])
Provide an array of items, and another array of items specifying the relative weights and Chance will select one of those items, obeying the specified weight.
For example, the following code:
chance.weighted(['a', 'b'], [100, 1]);
=> 'a'
Will generate 'a'
100 times more often than 'b'
but still choose one or the other randomly.
The weights are all relative, so if you have more than just two it will ensure that all items are generated relative to all of the weights.
For example, the following code:
chance.weighted(['a', 'b', 'c', 'd'], [1, 2, 3, 4]);
=> 'c'
Will generate a letter from the array but will pick 'b'
twice as often as it picks 'a'
and will pick 'c'
three times as often as it picks 'a'
and will pick 'd'
four times as often as it will pick 'a'
and will pick 'd'
two times as often as it will pick 'b'
.
The weights can be whole numbers as shown above or fractions.
chance.weighted(['a', 'b', 'c', 'd'], [0.1, 0.2, 0.3, 0.4]);
=> 'd'
There is no requirement that the weights sum to anything in particular, they are all compared relative to each other so all of the following are equivalent:
chance.weighted(['a', 'b', 'c', 'd'], [1, 2, 3, 4]);
chance.weighted(['a', 'b', 'c', 'd'], [0.1, 0.2, 0.3, 0.4]);
chance.weighted(['a', 'b', 'c', 'd'], [100, 200, 300, 400]);
chance.weighted(['a', 'b', 'c', 'd'], [17, 34, 51, 68]);
chance.weighted(['a', 'b', 'c', 'd'], [0.17, 0.34, 0.51, 0.68]);
Recall JavaScript has first class functions so you could do something like the following:
chance.weighted([chance.fbid, chance.twitter, chance.ip], [10, 5, 1])();
=> 10000345166213
That will pick one of the Chance methods with the relative weights specified and then immediately invoke it, so it will return a random fbid twice as often as it will return a twitter handle (because 10/5 is 2) and an fbid 10 times more often than it will return a random ip address (because 10/1 is 10). It will return a random twitter handle 5 times more often than it will return an ip address (because 5/1 is 5).
Todo

True Random
By default, the underlying random() is based on the Mersenne Twister. This is rad for repeatability, so given a seed a “random” sequence can be recreated, but it’s only pseudorandom.
There is nothing that would prevent this library from choosing, on instantiation, another random underbase though so in theory this whole library could work with a “true” random base.
Getting it to be true random would require some external entropy somehow and this gets tricky when putting this in Node or something. The usual “move your mouse to generate entropy” won’t work. I considered integrating with http://www.random.org but that would involve network latency which may be undesired and may work differently in Node or in the browser.
Anyway, none of these are insurmountable, but are tricky.

Regex
It would be awesome to specify some sort of regex indicating that some things should be replaced within a word.

More Generators!!
This is a work in progress!! Expect the current generators to continue as stable (and we have automated tests to help ensure that) but we will be constantly adding more.

Internationalization
At current, most of the address helpers are very UScentric. Fix that!

Better names
The Social Security page has a data dump of the top 1000 baby names. Use it to provide better random names that don’t just look like gibberish but are actual names.
Change Log
0.8.0
— 11 Sep 2015
— diff
 Moved the CLI out into its own repo/project, now at https://github.com/victorquinn/chancejscli. Minor version bump due to this potentially breaking change.
 Added new generators: country(), mrz(), avatar(), md5()
 Better jsdoc comments
 Automated coveralls test coverage report
 Bugfixes
0.7.0
— 05 Dec 2014
— diff
 Now with cli support! after
npm install g chance
you can run chance <generator_name>
on the command line and get a random result! Many thanks @oliversalzburg for this excellent addition!
 Added new generators: android_id(), bb_pin(), cpnj(), suffix(), wp7_anid(), wp8_anid(), url()
 Now with webworker support
 Now with UK and France phones
 Now allowing strings to be provided as the seed for more convenient testing
0.6.1
— 03 Sep 2014
— diff
 Add a bunch of new generators including: altitude(), apple_token() cpf(), currency(), currency_pair(), depth(), geohash(), get(), mac_address(), n(), set(), ssn(), unique(), weighted()
 Data now separated and replaceable via set(). Much better for internationalization or cases where the defaults are inadequate.
 New options for:
 email()  can now specify length of word before @
 name_prefix()  now can specify gender
 Possibly breaking changes (from 0.5.x):
 age()  now default age range is far more sensical but this means it is generally lower (default max used to be 120 now only 65)
 guid()  now returns all lowercase to accord with the majority of uses in the wild
 states()  now only returns US states by default, territories and armed forces by flag
0.5.5
— 16 Mar 2014
— diff
 Add range parameters to latitude() and longitude() so range can be bounded
 Add pad() helper
 Add google_analytics generator
 Now allowing for creation of chance instance without using the
new
keyword to simplify usage in Node.js
0.5.4
— 17 Dec 2013
— diff
 Add tv()
 Fix issue with negative dollar amounts
 Fix component.json so it works as expected
0.5.3
— 08 Nov 2013
— diff
 Revamp date() a bit to fix a bug, clean up the code, add finer grained randomity
 Add hammertime(), second(), millisecond()
0.5.2
— 05 Nov 2013
— diff
 Incorporate valid GUID generator pull request
 Add support for component
0.5.1
— 29 Oct 2013
— diff
 Fix a minor bug in the new date() function. See Issue 32 on Github for more details.
0.5.0
— 27 Oct 2013
— diff
 Bugfixes: shuffle() was destroying incoming array, color() was ignoring default options
 Tweaks to existing methods: allow pick() to return multiple elements, better first() and last() using actual names
 Added yet more generators: age(), birthday(), date(), gender(), hashtag(), klout()
 Now with Mixin support for extending Chance!
0.4.3
— 31 Jul 2013
— diff
 Added yet more generators: color(), hash()
 Major refactor of options handling to be much more DRY
 Now with NANP support for phones
 Other misc. refactoring to make things more clean
0.4.2
— 25 Jul 2013
— diff
 Added yet more generators, rpg(), d30()
 Added support for Bower
0.4.1
— 25 Jul 2013
— diff
 Added yet more generators, radio(), shuffle(), ipv6()
0.4.0
— 18 Jul 2013
— diff
 Added a ton more generators
 Added floating point generation
 Added ability to specify arbitrary random function
 Added minified version
0.3.3
— 01 Jul 2013
— diff
 Add floating()
 Add latitude(), longitude(), coordinates() using floating() as the base
0.3.2
— 01 Jul 2013
— diff
 Incorporate more pull requests for bug fixes
 Now with Travis CI for automated running of tests
 Add first(), last() and prefix()
0.3.1
— 25 Jun 2013
— diff
 Added domain(), email(), and ip()
 Pulled in some pull requests to fix minor bugs
0.3.0
— 23 Jun 2013
— diff
 Updated README to include more info on usage
 Added most text generators for character, string, syllable, word, phone number, more
 Added name generators
 Added address generators and guid
0.2.1
— 22 Jun 2013
— diff
 Updated README to include more info on usage
 Added most text generators for character, string, syllable, word
 Added address generators and guid
0.2
— 22 Jun 2013
— diff
 Now with a Mersenne Twister rather than Math.random() as the base so tests are
repeatable.
 Restructured Chance as a module rather than a singleton
 Constructor now takes a seed which can be used to instantiate a new copy with a
Mersenne Twister base
 Added some dice
0.1
— 21 Jun 2013
First Release! Barely any generators.