Skip to content

Instantly share code, notes, and snippets.

@JanneSalokoski
Last active December 28, 2016 07:27
Show Gist options
  • Save JanneSalokoski/a520c8c51c7a670c4ffd2a838ad6d972 to your computer and use it in GitHub Desktop.
Save JanneSalokoski/a520c8c51c7a670c4ffd2a838ad6d972 to your computer and use it in GitHub Desktop.
Utilities.js is a 'library' of generally useful functions not included in JavaScript standard libraries.

Utilities.js

Description...

Utilities.get_random_integer()

The Utilities.get_random_integer() function returns a pseudo-random integer number in the range [min, max] or [min, max), depending on its arguments.

Syntax

Utilities.get_random_integer(min, max, mode)

Parameters

min

A number.

Minimum value of the range from which the random integer is returned. Minimum value is always included in the range. Defaults to 0 if no value is given.

max

A number.

Maximum value the range from which the random integer is returned. Maximum value is included in the range in inclusive mode, but excluded in exclusive mode. Defaults to 1 if no value is given.

mode

A string. Either "inclusive" or "exclusive". Defines whether to include or exclude maximum value from the range from which an integer is returned.

Examples

Utilities.get_random_integer();                     // 0 - 1
Utilities.get_random_integer(0, 5);                 // 0 - 5
Utilities.get_random_integer(0, 5, "exclusive")     // 0 - 4
var Utilities = function () {}
Utilities.get_random_integer = function (min, max, mode)
{
// Get a random integer between min and max values either
// excluding the max value or including it
"use strict;"
// If parameters are missing, assign default values
if (min === undefined) { var min = 0; } // min defaults to 0
if (max === undefined) { var max = 1; } // max defaults to 1
if (mode === undefined) { var mode = "inclusive" } // mode defaults to inclusive
// Check that min < max as it should be
if (min > max)
{
throw new RangeError("Min is larger than max");
}
// Convert min and max into suitable integer values
min = Math.ceil(min);
max = Math.floor(max);
if (mode === "inclusive")
{
// Inclusive mode will include max value
return Math.floor(Math.random() * (max - min + 1)) + min;
}
else if (mode === "exclusive")
{
// Exclusive mode will exclude max value
return Math.floor(Math.random() * (max - min)) + min;
}
else
{
// Throw an error if mode is not inclusive nor exclusive
throw new SyntaxError("Unknown mode " + mode);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment