Skip to content

Instantly share code, notes, and snippets.

@wheeyls
Created February 29, 2012 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wheeyls/1938128 to your computer and use it in GitHub Desktop.
Save wheeyls/1938128 to your computer and use it in GitHub Desktop.
Stream fiddling - concatenate arrays into functional list, async processing
function keyValuePairs(callback) {
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6].forEach(function (i) {
callback(i);
});
}
function numbers(callback) {
for(var i = 0; i < 3; i++) {
callback([1,2,3]);
}
}
function individual(stream) {
return function(callback) {
stream(function(value) {
for(var i=0, ii = value.length; i<ii; i++) {
callback(value[i]);
}
});
};
}
function asyncStack(stream, delay) {
var list = [],
timer = null;
delay = delay || 250;
return function (callback) {
var process = function () {
if(list.length > 0) {
callback(list.pop());
} else {
clearTimeout(timer);
timer = null;
}
};
stream(function(value) {
list.push(value);
timer = timer || setInterval(process, delay);
});
};
}
function print(stream) {
stream(function(v) {
console.log(v);
});
}
print(asyncStack(individual(numbers), 100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment