Loading...
beginner
Problem 03 • Step 03
Inject the Randomness
Your randomInRange works, but testing it still requires a loop. Run it 200 times and hope the bug shows up. That is a statistical test. It is slow and it can occasionally pass even when the code is wrong.
The root cause: randomInRange creates its own randomness by calling Math.random() internally. You have no way to control it from outside.
The fix is simple: pass the random function in as an argument.
// Before: randomness is hidden inside
function randomInRange(max) {
return Math.floor(Math.random() * max);
}
// After: randomness is passed in
function randomInRange(max, random) {
return /* */;
}
This idea has a name: dependency injection. Instead of a function reaching out for something it needs (Math.random), you hand it in from outside. The function does not know or care whether it gets real randomness or a fake. It just calls whatever you give it.
Your task
- Rewrite
randomInRange(max, random)to use the providedrandomfunction instead ofMath.random - Rewrite
randomWord(list, random)to accept arandomfunction and pass it through torandomInRange - Write deterministic tests. No loops needed. Pass in a function that always returns the same value and check the exact result.