Skip to content

Instantly share code, notes, and snippets.

@thewhodidthis
Last active August 8, 2021 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thewhodidthis/1cbd1736c7f5320c11cce08c9db7ec04 to your computer and use it in GitHub Desktop.
Save thewhodidthis/1cbd1736c7f5320c11cce08c9db7ec04 to your computer and use it in GitHub Desktop.
Towards a NumPy inspired bound random integer producer
const assert = require('assert');
// Produce random (signed) integers from min inclusive to max exclusive
function randint(min = 0, max) {
let lo = min;
let hi = max;
if (typeof max === 'undefined') {
hi = lo;
lo = 0;
}
if (hi < lo) {
throw Error('min need be less than max please');
}
return Math.floor(Math.random() * (hi - lo)) + lo;
}
for (let i = 0; i < 100; i += 1) {
// Calling sans arguments gives back zero no matter what
assert.equal(randint(), 0);
}
for (let i = 0; i < 100; i += 1) {
// Same when calling with a min of one sans max
assert.equal(randint(1), 0);
}
// Expect min to be zero, max to be one, result to be zero
assert(randint(1) >= 0 === randint(1) < 1);
// Same when calling with a min of one sans max
assert.equal(randint(1), 0);
for (let i = 0; i < 100; i += 1) {
// Same with null
assert.equal(randint(null), 0);
}
for (let i = 100; i > 0; i -= 1) {
// Try out a few ranges in the positive
assert(randint(i) < i);
}
for (let i = -99; i < 0; i += 1) {
// What happens when using negative parameters?
assert(randint(2 * i, i) <= i);
}
try {
randint(0, -10)
} catch ({ message }) {
assert.equal(message, 'min need be less than max please');
}
@thewhodidthis
Copy link
Author

thewhodidthis commented Jul 28, 2020

# Tested with Node.js 12.18.1
git clone https://gist.github.com/1cbd1736c7f5320c11cce08c9db7ec04.git randint
cd randint
node randint.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment