Skip to content

Instantly share code, notes, and snippets.

View yelouafi's full-sized avatar

Yassine Elouafi yelouafi

View GitHub Profile
/*
The MIT License (MIT)
Copyright (c) 2014
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
/*************************************************/
/************* EventStream ***********************/
/*************************************************/
function EventStream(binder) {
this.binder = binder;
this.reset();
}
EventStream.prototype.reset = function() {
this.lastTime = 0;
@yelouafi
yelouafi / adt.js
Created April 24, 2015 11:31
Algebraic Data Types in javascript (see http://tech.pro/blog/6885/javascript-and-type-thinking)
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 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)))