Last active
September 3, 2024 16:07
-
-
Save ourmaninamsterdam/5ac8b9b060d4459a0735a2140350cc4b to your computer and use it in GitHub Desktop.
Generators: random numbers
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
function random(max: number) { | |
return Math.floor(Math.random() * max) | |
} | |
function* numberGenerator(limit: number) { | |
let current = 0; | |
let attempts = 0 | |
try { | |
while(current <= limit) { | |
current = random(7); | |
attempts++; | |
yield { current, attempts }; | |
} | |
} finally { | |
console.log(`It took ${attempts} attempts to get a random number greater than ${limit}.`); | |
console.log(`The final number was ${current}`); | |
yield { current, attempts }; | |
} | |
} | |
const numberGen = numberGenerator(5); | |
let result = numberGen.next(); | |
while(!result.done) { | |
console.log(result.value); | |
result = numberGen.next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment