Simple collection of tools for generating random behaviour in Javascript. Uses a Mersenne Twister for more accurate random behaviour and repeatability.
Try out the test page in your browser.
You can use Chancer on the server side with Node.js and npm:
npm install chancer
you can then include Chancer in your script by using require:
var chancer = require('chancer');
On the client side, you can include Chancer in your page (found in build/chancer.js):
<script src="chancer.js"></script>
If you're including via a <script>
tag, chancer
is available as a global variable.
You can specify a particular seed in order to get a repeatable random sequence:
Generates a seed that will always produce the same random sequence
num: (number) Integer to use as seed
chancer.seed(123);
Generates a floating-point number between 0 and 1
return: (float) Returns the floating point number
chancer.random(); // 0.32831766246818006
Generates a floating-point number between min (inclusive) and max (exclusive)
min: (number) Minimum inclusive number
max: (number) Maximum exclusive number
return: (float) Returns the floating point number
chancer.float(1, 10); // 2.794354454614222
Generates an integer between min (inclusive) and max (inclusive)
min: (number) Minimum inclusive number
max: (number) Maximum inclusive number
return: (integer) Returns the integer number
chancer.int(1, 10); // 3
Generates a 0 or 1 to represent a coin toss
Optionally associate any other values for the coin sides (true/false, yes/no, heads/tails, etc)
heads: Value for the head
tails: Value for the tails
return: Returns the chosen value
chancer.coinToss(); // 1
chancer.coinToss(true, false); // true
chancer.coinToss('heads', 'tails'); // tails
Generates a random item from an array
arr: (array) Array of items
return: (integer) Returns the randomly selected item
chancer.fromArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]); // 6
Generates an array shuffled into a random order
arr: (array) Array of items
return: (array) Returns the array shuffled into a random order
chancer.shuffleArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]); // [7, 3, 9, 4, 1, 6, 2, 5, 8]
Generates an array of integers between min (inclusive) and max (inclusive)
If no total specified return all possible values between min and max
min: (number) Minimum inclusive number
max: (number) Maximum inclusive number
total: (number) Total number of results | all
return: (array) Returns the chosen values
chancer.fillArray(1,10); // [3, 5, 4, 1, 6, 7, 8, 2, 10, 9]
chancer.fillArray(1,100,10); // [40, 66, 74, 39, 17, 99, 50, 70, 6, 15]
Generates a random value as a universally unique identifier (UUID) version 4 (RFC4122)
return: (string) Returns string representation of a UUIDv4
chancer.uuid(); // 73f765b2-958a-45fb-be10-b9fcebdd6838
Tested in the following browsers
Chrome | Opera | Firefox | Safari | IE | iOS | Android | WindowsPhone |
---|---|---|---|---|---|---|---|
3+ | 2.2+ | 8.1+ |
Chancer is licensed under the MIT license.
Copyright © 2015, Alex Kilgour