Skip to content

Instantly share code, notes, and snippets.

@ourmaninamsterdam
Last active September 3, 2024 16:07
Show Gist options
  • Save ourmaninamsterdam/5ac8b9b060d4459a0735a2140350cc4b to your computer and use it in GitHub Desktop.
Save ourmaninamsterdam/5ac8b9b060d4459a0735a2140350cc4b to your computer and use it in GitHub Desktop.
Generators: random numbers
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