Skip to content

Instantly share code, notes, and snippets.

@toddbranch
Last active December 8, 2015 17:11
Show Gist options
  • Save toddbranch/e9169ccaf7498006bc5d to your computer and use it in GitHub Desktop.
Save toddbranch/e9169ccaf7498006bc5d to your computer and use it in GitHub Desktop.
randomFromStream
function randomFromStream() {
var length = 0;
var result = null;
var potentialResult;
while(potentialResult = gfs()) {
length += 1;
if (Math.floor(Math.random() * length) === 0) {
result = potentialResult;
}
}
return result;
}
var result = randomFromStream();
function randomFromStream(currentResult, length) {
var potentialResult = gfs();
// no more numbers in stream
if (potentialResult === null) {
return currentResult;
}
length += 1;
if (Math.floor(Math.random() * length) === 0) {
currentResult = potentialResult;
}
return randomFromStream(currentResult, length);
}
var result = randomFromStream(null, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment