Skip to content

Instantly share code, notes, and snippets.

@dtipson
Created August 3, 2015 14:31
Show Gist options
  • Save dtipson/3dd715c04ffd79500f27 to your computer and use it in GitHub Desktop.
Save dtipson/3dd715c04ffd79500f27 to your computer and use it in GitHub Desktop.
function addOne(n){ return n+1; }
function logger(){ console.log.apply(console,arguments); return }
//Promise unit
function unit(n){ return $.Deferred().resolve(n); }
//make a simple function into a function that returns a Promise
function lift(fn){
return function(v){
return $.Deferred().resolve(fn(v)||v);//if no return value, pass through original value
};
}
//bind promises together
function bind(apromise, promisefn){
return apromise.then(function(x){
return promisefn(x);
});
}
//[a] -> [a -> [b]] -> [b]
var pipe = function(x, functions) {
for (var i = 0, n = functions.length; i < n; i++) {
x = bind(x, functions[i]);
}
return x;
};
var liftedAddOne = lift(addOne);
var liftedLog = lift(logger);
var pause1000 = function(val){ return $.Deferred(function(dfd){ window.setTimeout(function(){ dfd.resolve(val); },1000); }); };
pipe(
unit(5),//starting point
[
liftedAddOne,//list
liftedAddOne,//of functions
liftedLog,//that all return chainable promises
pause1000,//and thus can be .then'd together in a series
liftedAddOne,//which defines an entire program
liftedAddOne,
liftedLog
]
).then(null,function(){
console.log.bind(console,'catch and report errors');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment