diff --git a/src/algorithms/lib.js b/src/algorithms/lib.js index 2dc611c..f2a27b3 100644 --- a/src/algorithms/lib.js +++ b/src/algorithms/lib.js @@ -1,4 +1,4 @@ -// Get a random number between minimum and maximum number +// Get a random integer between minimum and maximum numbers (inclusive) export function randomNum(min, max) { - return Math.floor(Math.random() * (max - min) + min); + return Math.floor(Math.random() * (max - min + 1)) + min; } diff --git a/src/algorithms/lib.test.js b/src/algorithms/lib.test.js new file mode 100644 index 0000000..8023dbd --- /dev/null +++ b/src/algorithms/lib.test.js @@ -0,0 +1,16 @@ +import { randomNum } from './lib'; + +test('randomNum returns values within range and includes max', () => { + const min = 1; + const max = 2; + let sawMax = false; + for (let i = 0; i < 1000; i++) { + const value = randomNum(min, max); + expect(value).toBeGreaterThanOrEqual(min); + expect(value).toBeLessThanOrEqual(max); + if (value === max) { + sawMax = true; + } + } + expect(sawMax).toBe(true); +});