Skip to content

Instantly share code, notes, and snippets.

@coverslide
Created August 17, 2011 22:20
Show Gist options
  • Save coverslide/1152788 to your computer and use it in GitHub Desktop.
Save coverslide/1152788 to your computer and use it in GitHub Desktop.
A simple object wrapper that converts functions that return `undefined` to return an instance of the object instead, `chainifying` those calls
function chainify(obj, that){
if(typeof obj === 'object'){
that = that || {__object: obj}
for(var i in obj){
if(typeof obj[i] === 'function'){
that[i] = function(){
var ret = that.__object[i].apply(that.__object, arguments)
if(typeof ret === 'undefined')
return that
return ret
}
}
}
chainify(Object.getPrototypeOf === 'function' ? Object.getPrototypeOf(obj) : obj.__proto__, that)
return that
}
}
@djangofan
Copy link

In the Java world, we call this "fluent API". Some open source projects work this way like XMLSlurper, RestAssured, Commons CSV, JOOQ, jRTF, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment