Last active
August 8, 2021 16:23
-
-
Save thewhodidthis/1cbd1736c7f5320c11cce08c9db7ec04 to your computer and use it in GitHub Desktop.
Towards a NumPy inspired bound random integer producer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} |
Author
thewhodidthis
commented
Jul 28, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment