Skip to content

Instantly share code, notes, and snippets.

View yelouafi's full-sized avatar

Yassine Elouafi yelouafi

View GitHub Profile
/*************************************************/
/************* EventStream ***********************/
/*************************************************/
function EventStream(binder) {
this.binder = binder;
this.reset();
}
EventStream.prototype.reset = function() {
this.lastTime = 0;
function eachKey(obj, f) {
for(var key in obj) {
if( obj.hasOwnProperty(key) )
f(key, obj[key]);
}
}
function adtcase (base, proto, key) {
return (...args) => {
var inst = new base();
function toArray(args) {
return Array.prototype.slice.call(args);
}
function doLater(act) {
setTimeout(act, 0);
}
function eachKey(obj, f) {
for(var key in obj) {
"use strict";
class Emitter {
constructor() {
this.slots = [],
this.ends = [];
}
onValue(h) {
function Stream() {}
adt( Stream, {
Empty : new Stream(),
Abort : function (error) { return {error} },
Promise : function (promise) { return {promise} },
Cons : function (head, tail) { return {head, tail} }
})
const noop = () => {}
Stream.prototype.forEach = function(onNext, onError=noop, onComplete=noop) {
return this.isEmpty ? onComplete()
: this.isAbort ? onError(this.error) :
: this.isCons ? (
onNext(this.head),
this.tail.forEach(onNext, onError, onComplete))
: this.promise.then(
stream => stream.forEach(onNext, onError, onComplete),
Stream.prototype.log = function(prefix) {
this.forEach(
v => console.log(prefix, v),
err => console.log(prefix, ' error!!', err),
() => console.log(prefix, ' end.')
);
}
Stream.seq([1,2,3], 0, 1000).log('seq')
// map : (Stream a, a -> b) -> Stream b
Stream.prototype.map = function(f) {
return this.isEmpty || this.isAbort ? this
: this.isCons ? Stream.Cons(f(this.head), this.tail.map(f))
: Stream.Future(
this.promise.then(
s => s.map(f),
err => Stream.Abort(err)))
// anError : Object
// mapError : (Stream a, anError -> Stream a) => Stream a
Stream.prototype.mapError = function(f) {
return this.isEmpty ? this
: this.isAbort ? f(this.error)
: this.isCons ? Stream.Cons(this.head, this.tail.mapError(f))
: Stream.Future(
this.promise.then(
s => s.mapError(f),
Stream.Abort))
filter :: (a -> Bool) -> [a] -> [a]
filter _pred [] = []
filter pred (x:xs)
| pred x = x : filter pred xs
| otherwise = filter pred xs