Skip to content

Instantly share code, notes, and snippets.

View yelouafi's full-sized avatar

Yassine Elouafi yelouafi

View GitHub Profile
// concatAll : Stream (Stream a) -> Stream a
Stream.prototype.concatAll = function() {
return this.flatten( (s1, s2) => s1.concat(s2) );
}
// mergeMap : (Stream a, a -> Stream b) => Stream b
Stream.prototype.mergeMap = function(f) {
return this.map(f).mergeAll();
}
// example : log messages from a chat room
// login user returns a stream of messages from a logged user
loginUser : (name, password) -> Stream String
button.on('click').mergeMap( _ => loginUser(name, password) )
// concatMap : (Stream a, a -> Stream b) => Stream b
Stream.prototype.concatMap = function(f) {
return this.map(f).concatAll();
}
// example : log bodies from ajax responses
button.on('click').concatMap( _ => ajaxBody(url) )
// event : () => Promise
// throttle : (Stream a, event) => Stream a
Stream.prototype.throttle = function(event) {
return this.isEmpty || this.isAbort ? this
: this.isCons ?
Stream.Cons(this.head, this.tail.skipUntil(event()).throttle(event))
: Stream.Future(this.promise.then( s => s.throttle(event), Stream.Abort));
};
// undefined equivalent for streams
const undef = {}
// debounce : (Stream a, () => Promise) => Stream a
Stream.prototype.debounce = function(event, last=undef) {
return this.isEmpty || this.isAbort ?
(last !== undef ? Stream.Cons(last, this) : this)
: this.isCons ?
this.tail.debounce(event, this.head)
// sequence of elements from an array that occur at a fixed interval
// starting after an initial delay
// yields 1, 2 and 3 each second starting after five seconds
Stream.seq([1,2,3], 5000, 1000)
//stream of DOM events that occur until a promise is completed
// receives click events for 10 seconds
Stream.fromDomEvent(document.body, 'click', delay(10000) )
// Node events can also be thought as (possibly infinite) streams
import snabbdom from 'snabbdom';
const patch = snabbdom.init([ // Init patch function with choosen modules
require('snabbdom/modules/class'), // makes it easy to toggle classes
require('snabbdom/modules/props'), // for setting properties on DOM elements
require('snabbdom/modules/style'), // handles styling on elements with support for animations
require('snabbdom/modules/eventlisteners'), // attaches event listeners
]);
import h from 'snabbdom/h';
var vnode = h('div', {style: {fontWeight: 'bold'}}, 'Hello world');
patch(document.getElementById('placeholder'), vnode);
function view(currentDate) {
return h('div', 'Current date ' + currentDate);
}
var oldVnode = document.getElementById('placeholder');
setInterval( () => {
const newVnode = view(new Date());
oldVnode = patch(oldVnode, newVnode);
}, 1000);
function view(name) {
return h('div', [
h('input', {
props: { type: 'text', placeholder: 'Type your name' },
on : { input: update }
}),
h('hr'),
h('div', 'Hello ' + name)
]);
}