Created
February 29, 2012 05:23
-
-
Save wheeyls/1938128 to your computer and use it in GitHub Desktop.
Stream fiddling - concatenate arrays into functional list, async processing
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 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