Skip to content

Instantly share code, notes, and snippets.

@barneycarroll barneycarroll/returner.js
Last active Aug 29, 2015

Embed
What would you like to do?
returner is a convenience function that allows you to invoke mutator methods on arrays (or anything else) and return the mutated array itself rather than some arbitrary property of that array.
// returner is a convenience function that allows you to invoke mutator methods on arrays (or anything else)
// and return the mutated array itself rather than some arbitrary property of that array.
//
// Why?
// I have never been convenienced by the returned length of an array after pushing to it.
// I have often wanted to push to an array and return it with the same statement.
//
// Seriously? Like, when?
// Can I use a word in its own definition? At line 27, I want to modify an array and return it.
// Thanks to returner, I'm evaluating that as a function argument expression.
// Without it, I'd have to modify it in a separate line, then pass it as an argument.
//
// Usage:
// returner( [ 1, 2 ], 'push', 3 ); // -> [ 1, 2, 3 ]
// returner( [ 1, 2, 3], 'splice', 1, 1, 0 ); // -> [ 1, 0, 3 ]
//
// Allows chaining of native object & array mutator methods via chain method:
// returner.chain( [ 5, 6, 7 ] )( 'unshift', 4 )( 'splice', 2, 2, 5 ).value(); // -> [ 4, 5, 5 ]
function returner( obj, method ){
obj[ method ].apply( obj, Array.prototype.slice.call( arguments, 2 ) );
return obj;
}
returner.chain = function wrap( obj ){
function chainReturner(){
returner.apply( undefined, returner( Array.prototype.slice.call( arguments ), 'unshift', obj) );
return chainReturner;
}
chainReturner.value = function unWrap(){
return obj;
};
return chainReturner;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.