I'm trying to understand how the following zip function (esp. the invoke function) can be made more functional. The issue I've got is that the invoke method has to wait for both the left and right side to be filled before it can dispatch the values. The values have to be called in order so that the correct values are zipped, otherwise I would consider a curry/partial function to fulfill this.
Is there anything that I could use that could remove this hinderance.
function zip(state, a, b) {
var left = [];
var right = [];
function invoke() {
if (left.length > 0 && right.length > 0) {
state([left.shift(), right.shift()]);
}
}
a.foreach(function(v) {
left.push(v);
invoke();
});
b.foreach(function(v) {
right.push(v);
invoke();
});
}
Bellow is a simple example of what satisfies the zip function.
function Stream() {
var env = this;
env.subs = [];
env.id = setInterval(function() {
env.subs.forEach(function(f) {
f(Math.random());
});
}, ((Math.random() * 100) + 500) | 0);
}
Stream.prototype.foreach = function(f) {
this.subs.push(f);
}
zip(function(v) {
console.log(v);
}, new Stream(), new Stream());
Bonus: Removing mutable array.
See Question&Answers more detail:os