Skip to content

Instantly share code, notes, and snippets.

@datchley
Last active August 29, 2015 14:11
Show Gist options
  • Save datchley/704f6248a41b349e31d9 to your computer and use it in GitHub Desktop.
Save datchley/704f6248a41b349e31d9 to your computer and use it in GitHub Desktop.
A rudimentary, asychronous ES5 generator using Promises
/**
* Return a random number between min/max where the mean
* result is approximately the mode across a uniform distribution.
* @param min {Number} - lower limit of range (inclusive)
* @param max {Number} - upper limit of range (inclusive)
* @return {Function} - a function that returns a random number between 'min' and 'max'
*/
var genRandomFromRangeFn = function(min, max) {
return function() {
var res = Math.round(Math.random() * (max - min)) + min;
return res;
};
};
/**
* Async Function Generator: generates a function that returns a Promise that when
* resolved will have happend after a random interval in 'ms' between
* 'min' and 'max' (see #genRandomFromRangeFn)
* @param min {Number} - lower limit of range to generate random number within
* @param max {Number} - upper limit of range to generate random number within
* @return {Promise} - when fulfilled, it's value property will have
* two properties: iteration {Number} - the count for this value in sequence with the others
* period: {Number} - number of milliseconds waited before resolving
*/
var timedSequenceGenerator = function(min, max) {
var randomFromRange = genRandomFromRangeFn(min, max), // get a random number between min and max
count = 1;
return {
next: function() {
return new Promise(function(resolve, reject) {
// generate a random time period to wait between min,max (in ms)
var wait = randomFromRange() * 1000;
setTimeout(function() {
resolve({ value: { iteration: count++, period: wait }, done: false });
// console.log("[debug] iteration: %d, wait time = %d", count, wait);
}, wait);
});
}
};
};
var sequencer = timedSequenceGenerator(6, 9),
prev_promise = Promise.resolve(),
max_refresh = 20,
periods = [];
// Run a random wait period generated by sequence.next() for
// max_refresh times, in series (back to back).
while (max_refresh--) {
prev_promise = prev_promise.then(function() {
return sequencer.next();
})
.then(function(int) {
console.log("here");
console.log("tick (%d) waited %d ms", int.value.iteration, int.value.period)
})
.catch(function(err) {
console.log("error: ", err);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment