Skip to content

Instantly share code, notes, and snippets.

@micahasmith
Created July 12, 2012 20:01
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save micahasmith/3100561 to your computer and use it in GitHub Desktop.
objlit functional signature style, take one
/**
* Here's the idea:
* Lets see what we can do if we don't do function(err,cb) all the time
* and instead we do function(objlit)
*
* Any advantages to instead wrapping it in one variable?
*/
// an example of what this may look like
var theobj={
err:{}, // errrrrrr
cb:function(){}, // callback
params:[] // the new "arguments"-- think function args
};
//generic function for point making purposes, not important
var actOnIt=function(val){
console.log("i'm going to act on ",val);
return "okgood!";
}
//also generic and unimportant... move on
var handleError=function(err){
console.error(err);
};
// old style, err then something then cb
// not really what i like
// but for node's sake i will oblige
var oldStyle=function(err,something,cb){
var result;
//did we error?
//lets do this in every function.
if(err!==null) {
handleError(err);
}
//get some work done
if(something){
result=actOnIt(something);
}
//pass it along
cb(result);
}
// here's what i'd like
// wow so clean and simple
var newStyle = function(something){
var result;
if(something){
result=actOnIt(something);
}
return result;
}
// maybe theres functional prog-style benefits this?
// maybe to make node less callback style? (can we do this? feel free to correct me)
//
// since its all in one object, this is super simple to achieve
// with the old style, its (error?, args... , callback) --
// where things are in the signature fluctuate in terms of location
// , if they exist, how many they are...
function wrapIt(fn){
return function(objlit){
//take care of errors, the same way ONCE
if(objlit.err){
globalErrorHandle(err);
}
//curry the params it would take into it
//pass it to the callback
//keeping our objlit style
objlit.cb({
params:fn.apply(fn,objlit.params)
});
};
}
// lets try the new way--
// imagine just map-ing this against your library in an AOP fashion
// for here now i'll just do it manually, for just this function
var newway = wrapIt(newStyle);
newway({
params:["here's a value for something!"]
cb:console.log
});
//or you can do it the old way
//.... but you do have to do all the boilerplate over and over.
oldStyle(null,"here's a value",console.log);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment