Skip to content

Instantly share code, notes, and snippets.

@SimonRichardson
Last active December 20, 2015 23:29
Show Gist options
  • Select an option

  • Save SimonRichardson/6212588 to your computer and use it in GitHub Desktop.

Select an option

Save SimonRichardson/6212588 to your computer and use it in GitHub Desktop.
function foreach(a, f) {
var total,
i;
for (i = 0, total = a.length; i < total; i++) {
f(a[i]);
}
}
function Propagate(value){
this.value = value;
}
function Negate() {
}
function Stream(pulse) {
var siblings = [];
pulse(function(value){
for(var i = 0, total = siblings.length; i < total; i++) {
siblings[i](value);
}
});
this.fork = function(func) {
var binder;
siblings.push(function pulser(value) {
var propagation = func(value);
if (binder && propagation instanceof Propagate) {
binder(propagation.value);
} else {
binder = null;
// This could be done in a FP way.
var index = siblings.indexOf(pulser);
if (index >= 0) {
siblings.splice(index, 1);
}
}
});
return new Stream(function(pulse) {
binder = pulse;
});
};
}
Stream.prototype.foreach = function(f) {
return this.fork(f);
};
Stream.prototype.map = function(f) {
return this.fork(function(value) {
return new Propagate(f(value));
});
};
function StreamBool(stream){
this.stream = stream;
}
StreamBool.prototype.not = function() {
return new StreamBool(this.stream.map(function(value) {
return !value;
}));
};
var stream = new Stream(function(pulse) {
setTimeout(function() {
pulse((Math.random() * 2) - 1);
}, 100);
});
stream.fork(function(value) {
console.log('Foreach 1 A', value);
return new Propagate(value);
}).foreach(function(value) {
console.log('Foreach 2 A', value);
return new Negate();
}).foreach(function(value) {
console.log('Foreach 3 A', value);
});
stream.fork(function(value) {
console.log('Foreach 1 B', value);
return new Propagate(value);
});
stream.map(function(value) {
console.log('Map 1', value);
return value + 1;
}).map(function(value) {
console.log('Map 2', value);
return value + 1;
});
var bool = new StreamBool(stream);
bool.not().stream.foreach(function(value) {
console.log('Not 1', value);
});
@SimonRichardson
Copy link
Copy Markdown
Author

Outputs:
// Foreach 1 A, 0.8283838094212115
// Foreach 2 A, 0.8283838094212115
// Foreach 1 B, 0.8283838094212115
// Map 1, 0.8283838094212115
// Map 2, 1.8283838094212115
// Not 1, false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment